Java8 stream style to convert list of key values ​​to map?

I want to convert a list, such as [k1, v1, k2, v2], into a map like {k1: v1, k2: v2}. Source:

List<Object> params = Arrays.asList("k1", "v1", "k2", "v2"); Map<String, Object> map = new HashMap<>(); for(int i = 0; i < params.size(); i+=2) { String key = (String)params.get(i); Object value = params.get(i + 1); map.put(key, value); } System.out.println(map); // => {k1=v1, k2=v2} 

Then I want to convert it to java8 stream style? How?

+5
source share
2 answers

You can use this, but to be honest, your for loop is much more readable. I would try to avoid creating such a list in the first place and should have List<SomePair> , where SomePair contains the key and value.

  List<Object> params = Arrays.asList("k1", "v1", "k2", "v2"); Map<String, Object> map = IntStream.range(0, params.size() / 2) .collect(HashMap::new, (m, i) -> m.put((String) params.get(i * 2), params.get(i * 2 + 1)), HashMap::putAll); System.out.println(map); // => {k1=v1, k2=v2} 
+2
source

Alternatively, using Stream , you can simply use the good Iterator and call next to get the next element. Of course, this will not succeed if the list does not have an even number of elements.

 Map<String, Object> map = new HashMap<>(); Iterator<Object> iter = params.iterator(); iter.forEachRemaining(x -> map.put((String) x, iter.next())); 
+2
source

Source: https://habr.com/ru/post/1264260/


All Articles