简体   繁体   中英

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 .

I would like to group Task objects by project's ids. 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. 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 ).

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).

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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