Bruce
Bruce

Reputation: 8849

Java 8 Convert 2D array into Map with key duplication check

In java 8 how to convert a 2D array into Map using stream(). If a key value is already present it should update value as well.

String[][] array=new String[][]{{"a","b"},{"a","c"},{"b","d"}};
HashMap<String,String> map=new HashMap<String,String>();
for(String[] arr:array){
   map.put(arr[0],arr[1]);
}

I tried this

map=Arrays.stream(array).collect(Collectors.toMap(x->x[0],x->x[1]));

Error

Error:(38, 45) java: incompatible types: inference variable R has incompatible bounds equality constraints: java.util.Map upper bounds: java.util.HashMap,java.lang.Object

Upvotes: 4

Views: 4232

Answers (1)

emesx
emesx

Reputation: 12755

Add an operator that merges duplicate keys:

String[][] array = new String[][]{{"a", "b"}, {"a", "c"}, {"b", "d"}};

Map<String, String> m = Arrays.stream(array)
                              .collect(Collectors.toMap(  kv -> kv[0],
                                                          kv -> kv[1],
                                                          (oldV, newV) -> newV)
                                                       ));

Formatting those one-liners will be an issue one day..

Upvotes: 6

Related Questions