简体   繁体   English

按嵌套字段对元素进行分组

[英]Group elements by nested field

I have the following domain classes:我有以下域类:

public class Task {
    private Project project;
}
public class Project{
    private int id;
}

And I have a list of tasks called tasks .我有一个名为tasks的任务列表。

I would like to group Task objects by project's ids.我想按项目的 ID 对Task对象进行分组。 The resulting type of the的结果类型

I tried the code shown below.我尝试了下面显示的代码。 But it doesn't group objects by ids, but rather groups based on whether the key is the same object or not.但它不会按 id 对对象进行分组,而是根据键是否相同 object 进行分组。 I found duplicates, I tried to get rid of them, but I couldn't make it work.我发现了重复项,我试图摆脱它们,但我无法让它发挥作用。

tasks.stream().collect(Collectors.groupingBy(task::getProject));

I want something like that我想要那样的东西

tasks.stream().collect(Collectors.groupingBy(task::getProject::getId));

But unfortunately, I couldn't do that.但不幸的是,我不能那样做。

As @n247s has pointed out in the comments, the syntax of the Method reference you're using is incorrect - you can't chain method reference ( for more details, refer to the official tutorial ).正如@n247s在评论中指出的那样,您使用的方法引用的语法不正确- 您不能链接方法引用( 有关详细信息,请参阅官方教程)。

The keyExtractor Function you need can be expressed only using a Lambda expression because in order to create a Method reference to an instance method of a Particular Object you need to have a reference to it, you don't have it (it's not possible in this case).您需要的keyExtractor Function只能使用 Lambda 表达式来表达,因为为了创建特定 Object的实例方法的方法引用,您需要引用它,但您没有它(这不可能)案件)。

Here's the only option:这是唯一的选择:

task -> task.getProject().getId()

It would be possible to create a Method reference of this type using a method of the nested object if you had a reference to the enclosing object stored somewhere.如果您有对存储在某处的封闭 object 的引用,则可以使用嵌套 object 的方法创建此类型的方法引用。 For instance, like that:比如像这样:

Task foo = new Task();
Function<Task, Integer> taskToId = foo.getProject()::getId;

But since you're dialing with a stream element, it not feasible.但由于您使用 stream 元素拨号,因此不可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM