Home > Net >  Group elements by nested field
Group elements by nested field

Time:11-15

I would like to group tasks by project ids. I tried like below. But it doesnt grouping by their ids. Grouping by same object or not. I found duplicate questions i tried them but i couldnt make it work. All made of so complicated for me. tasks.stream().collect(Collectors.groupingBy(task::getProject)); I want something like tasks.stream().collect(Collectors.groupingBy(task::getProject::getId)); But unfortunately i couldnt do.

My task class public class Task { Project project; }

My project class public class Project{ int id; }

if I use tasks.stream().collect(Collectors.groupingBy(task::getProject)); it returns Map<Project, List<Task>> project. I want to return same this by grouping by their ids.

CodePudding user response:

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.

  • Related