Skip to content
Advertisement

How to use groupingby() to create a map from a stream in java, but grouping by not only by an attribute

I have a stream from elements of a class x. One of the arributes (t) of the class x is from type LocalDateTime and I need to group the elements by hours.

I tried something like this:

Map<Integer, List<x>> m = stream.collect(Collectors.groupingBy(x::t.getHour));

But this syntax doesn´t work, any other idea of what i might be able to do?

Advertisement

Answer

The attempt is actually pretty close. We can achieve the desired result with the following code snippet:

Map<Integer, List<X>> map = 
    stream.collect(Collectors.groupingBy(x -> x.getT().getHour()));;

Ideone.com demo

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement