Ismail
Ismail

Reputation: 2962

Stream collect groupingBy output customization

I have a JAVA class described as bellow:

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, 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 steams of course:

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.

Upvotes: 0

Views: 141

Answers (1)

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.

Upvotes: 3

Related Questions