1

i have two list;

val keys: List<String> = listOf("key1", "key2", "key3"...)
val values: List<String> = listOf("value1", "value2", "value3"...)

How can i merge them into one List<Hashmap<Key,Value>>? like;

println(List<Hashmap<Key,Value>>): [[key1 = value1], [key2 = value2], [key3 = value3]...

dpr
  • 8,675
  • 3
  • 32
  • 57
Cinemacom
  • 47
  • 1
  • 1
  • 5
  • 2
    The operation is called zip: https://www.baeldung.com/java-collections-zip – dpr Apr 14 '20 at 13:35
  • Does this answer your question? [How do I join two lists in Java?](https://stackoverflow.com/questions/189559/how-do-i-join-two-lists-in-java) – Nico Haase Apr 14 '20 at 13:40

2 Answers2

6

In idiomatic Kotlin, that would look like this:

val keys: List<String> = listOf("key1", "key2", "key3")
val values: List<String> = listOf("value1", "value2", "value3")

val result = keys.zip(values).map { hashMapOf(it) }

(runnable demo)

Here, hashMapOf(...) accepts pairs (Pair<K, V>), and that's exactly the elements that zip produces.

Alternatively, you can use the overload of zip that accepts a lambda and maps the pairs without an additional call to map:

val result = keys.zip(values) { k, v -> hashMapOf(k to v) }

(runnable demo)

The result is a list of maps, each containing a single key mapped to the value.


An opposite option is to create a single map containing all of the pairs, which can be produced as follows:

val result = HashMap(keys.zip(values).toMap())

(runnable demo)

hotkey
  • 111,884
  • 27
  • 298
  • 285
  • 2
    @Tenfour04 Isn't that what the question author asked for? A list of hash maps, each containing a single key mapped to the value, I mean. – hotkey Apr 14 '20 at 14:56
  • 1
    @hotkey It might be nice to include `keys.zip(values).toMap()` as well to illustrate that a single map is possible. – Adam Apr 14 '20 at 15:00
  • @Adam, thanks for the suggestion! I've updated the answer. – hotkey Apr 14 '20 at 15:03
0

I would have done like this. Create your own class

class MyMap{
   String key;
   String value;
}

and then

 List<MyMap> newList = new ArrayList<>();
for (int i=0;i<keys.size();i++){
      newList.add(new MyMap(keys.get(i),values.get(i)));
 }
RIPAN
  • 1,936
  • 3
  • 14
  • 24