流式处理 collect groupingBy 输出定制

huangapple go评论94阅读模式
英文:

Stream collect groupingBy output customization

问题

我有一个JAVA类,如下所示:

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

}

现在我有一个Hello对象的列表,我想按field1对列表元素进行分组。我的问题是,我只想得到一组field3作为分组元素,而不是所有Hello对象的字段。

例如,作为输出,我想要得到一个映射:

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

我尝试使用流来实现它,当然:

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

就像上面这样,我会得到一个由field1映射的Hello对象的集合,不幸的是,这不是我想要的。

英文:

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.

答案1

得分: 3

我认为你正在寻找 Collectors.mapping

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

总的来说,最好随时准备好Collectors的Javadoc,因为有许多有用的组合操作(比如这个mapping和它的逆操作collectingAndThen),当你有类似的问题时,浏览列表以找到合适的工具会非常有帮助。

英文:

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.

huangapple
  • 本文由 发表于 2020年9月18日 00:19:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63942217.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定