I have a List
of strings which are actually keys and values: "key1", "value1", "key2", "value2", ...
(every odd item is a key, every even — value). How can I convert it to Map
like this "key1" -> "value1", "key2" -> "value2", ...
in a beautiful way?
Using Collectors. toMap() method: This method includes creation of a list of the student objects, and uses Collectors. toMap() to convert it into a Map.
And to be complete note that you can use a binary operator if your function is not bijective. For example let's consider this List and the mapping function that for an int value, compute the result of it modulo 3: List<Integer> intList = Arrays. asList(1, 2, 3, 4, 5, 6); Map<String, Integer> map = intList.
Array List can be converted into HashMap, but the HashMap does not maintain the order of ArrayList. To maintain the order, we can use LinkedHashMap which is the implementation of HashMap.
You can simply do:
Iterator<String> it = list.iterator();
while(it.hasNext()) {
map.put(it.next(), it.next());
}
This will be more efficient than using the get(index)
method (in case the list implementation does not allow random access)
Here's a relatively neat way:
var map = IntStream.range(0, list.size() / 2).boxed()
.collect(Collectors.toMap(i -> list.get(i * 2), i -> list.get(i * 2 + 1)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With