0

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.

3
  • 1
    I would like to achieve this using lambda in single line code. Why? Commented Sep 6, 2017 at 21:54
  • why do you need to group the Event based on groupId when all you want as an end result is an Event that has the highest evenId? if so just query the List<Event> if not then please elaborate... Commented Sep 6, 2017 at 22:08
  • or do you want the Maximum Event of each group? Commented Sep 6, 2017 at 22:12

1 Answer 1

1

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 ) );
Sign up to request clarification or add additional context in comments.

2 Comments

Think you mean > 0
Or replace (e1, e2) -> e1.getEventId().compareTo( e2.getEventId() ) > 0 ? e1 : e2 ) with BinaryOperator.maxBy(Comparator.comparingLong(Event::getEventId)) (looks better with static imports…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.