Jan Hornych
Jan Hornych

Reputation: 91

How to map two-dimensional array into HashMap using first dimension as keys with stream

I need map two dimensional array

String [][] values = {{key1, key2,...}, {value1, value2,...}}

into HashMap<String, String>.

I tried to use stream Arrays.stream(values).collect(Collectors.toMap(key -> key[0], value -> value[1])

I got key1=key2, value1=value2. I need key1=value1, key2=value2

Is there some solution using stream for this approach?

Upvotes: 2

Views: 501

Answers (1)

user8401765
user8401765

Reputation:

try using this:

 HashMap<String,String> map = 
        new HashMap<String, String>(IntStream
                                    .range(0,values[0].length)
                                    .boxed()
                                    .collect(Collectors.
                                             toMap(i -> values[0][i], i -> values[1][i])));

Upvotes: 3

Related Questions