javajava-streamcollectors

How to customize the output of Stream.groupingBy


I the following Java class:

public class Hello {
   
   public String field1;
   public String field2;
   public String field3;

}

Now I have a list of Hello objects, I want to group the list element by field1. My issue is that I want to have only a set of field3 as grouped elements, not all the Hello object fields.

For example, as output, I want to get a map:

field1Value1 -> [field3Value1, field3Value2, field3Value3]
field1Value2 -> [field3Value4, field3Value5, field3Value6]

I have tried to do it using streams:

HelloList.stream.collect(Collectors.groupingBy(Hello::field1, Collectors.toSet()));

Like above I will get a set of Hello objects mapped by field1. Unfortunately, that's not what I want.


Solution

  • I think you're looking for Collectors.mapping:

    helloList.stream()
        .collect(groupingBy(Hello::field1, mapping(Hello::field3, toSet())));
    

    In general, it's a good idea to have the Javadoc for Collectors handy, because there are a number of useful composition operations (such as this mapping and its inverse collectingAndThen), and there are enough that when you have a question like this it's useful to look over the list to find an appropriate tool.