Programmer
Programmer

Reputation: 325

Sorting and creating map using lambda in Java8

I have a list like

List<Event>

where Event has properties like eventId, eventName, groupId etc. There can be multiple events belonging to same group. I want a map like

Map<Long, Event>

where key is the groupId and Event is the one which has max eventId. So, basically I just want to sort list of events belonging to same group and then find out the one which has maximum event Id which can be used as a value. I am not sure how this can be achieved. Please assist.

I would like to achieve this using lambda in single line code.

Upvotes: 0

Views: 72

Answers (1)

tsolakp
tsolakp

Reputation: 5948

You can try something like this:

Map<Long, Event> result = events.stream().collect( 
Collectors.toMap( (e) -> e.getGroupid() , (e) -> e, 
(e1, e2) -> e1.getEventId().compareTo( e2.getEventId() ) > 0 ? e1 : e2 ) );

Upvotes: 1

Related Questions