4
votes

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

1
Well, this code will update the values... What's the problem then?fge
it gives an compile time error arraytype expectedBuru
nope i want to convert it using java 8 streamBuru
@DavidJones i just wanted know how above code be written in java 8. that is the question. i know these stuffsBuru

1 Answers

6
votes

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..