Java Stream - collecting rows of data in several rows with one column grouped into a set

I'm new to working with Java threads, so I apologize for any misunderstandings.

I want to use Collect on my stream to return a stream that has grouped strings that correspond to all elements, but one to the singular string into which this one element is added to the set.

For example, if my stream contains data:

[{12, "Apple", "Gala"},
 {12, "Apple", "Fuji"},
 {13, "Orange", "Navel"},
 {13, "Orange", "Valencia"}] 

After collecting for column 3, it will return a stream with data:

[{12, "Apple", ["Gala", "Fuji"]},
 {13, "Orange", ["Navel", "Valencia"]}]

Is this possible with a stream collection method? Any help is much appreciated!

Thank.

+4
source share
2 answers

, . , ,

getNumber, getType, getName.

, .

:

list.stream()
    .collect(Collectors.groupingBy(Fruit::getNumber,
        Collectors.groupingBy(Fruit::getName, Collectors.mapping(Fruit::getType, Collectors.toList())))));

HashMap hashmaps, :

{12={Apple=[Gala]}, 13={Orange=[Navel, Valencia]}}

Fruit:: getName Function.identity(), , fruit , .

+1

rextester

Map<Integer, Map<String, Set<String>>> fruitsByIdByType = 
                   fruits.stream()
                    .collect(Collectors.groupingBy(Fruit::getId, Collectors.groupingBy(Fruit::getName, Collectors.mapping(Fruit::getType, Collectors.toSet()))));
+1

Source: https://habr.com/ru/post/1673749/


All Articles