java stream groupingBy embedded objects

Viewed 319

I have couple of objects:

public class RequestHostel {
    private Hostel name;
}

and

public class Hostel {
    private String value;
}

and I would like to know if it is possible to group by the value of Hostel, something like

.stream().collect(Collectors.groupingBy(RequestHostel::getName::getValue, counting()))
2 Answers

You cannot chain method reference, but you can use lambda:

.stream().collect(Collectors.groupingBy(rh -> rh.getName().getValue(), counting()))

Or if you're not using these objects, you can simply map them:

.stream().map(RequestHostel::getName).collect(Collectors.groupingBy(Hotel::getValue, counting()))

You cannot chain method references as you did. But yes, you can use lambda for that:

Map<String, Long> countGroupedByValue = requestHostels.stream()
        .collect(Collectors.groupingBy(requestHostel -> requestHostel.getName().getValue(),
                Collectors.counting()));
Related