英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论