简体   繁体   中英

Java 8 stream- convert List<Integer[]> to Map<Integer,List<Integer>>

I want to convert the List<Integer[]> to Map<Integer,List<Integer>> . The Integer[] is of size two. Integer[0] is the key of the map and Integer[1] will be the value of the map.

Let's take an example. The input values are:

List<Integer[]> a=new ArrayList<>(5);
a.add(new Integer[] {1,2});
a.add(new Integer[] {1,3});
a.add(new Integer[] {1,15});
a.add(new Integer[] {2,11});
a.add(new Integer[] {2,7});

And the resulted output map will have two keys, 1 and 2.

The value of key 1 are 2,3 and 15.

The value of key 2 are 11 and 7.

Here's a stream that groups collected results on the first element of the array:

Map<Integer, List<Integer>> gouped = a.stream()
    .collect(Collectors.groupingBy(arr -> arr[0], 
             Collectors.mapping(arr -> arr[1], Collectors.toList())));

And that map is {1=[2, 3, 15], 2=[11, 7]}

Try this one

Map<Integer,List<Integer>> map = new HashMap<>();
a.stream().forEach(t -> {
                map.computeIfAbsent(t[0], ArrayList::new);
                map.get(t[0]).add(t[1]);
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM