Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert List of key/value strings to Map

Tags:

java

list

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?

like image 634
coquin Avatar asked Mar 18 '16 14:03

coquin


People also ask

Can we convert List to map in Java?

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.

How can we convert List to 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.

Can we convert ArrayList to map in Java?

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.


2 Answers

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)

like image 52
Jean Logeart Avatar answered Sep 17 '22 08:09

Jean Logeart


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)));
like image 20
sprinter Avatar answered Sep 20 '22 08:09

sprinter