Tanvi Jaywant
Tanvi Jaywant

Reputation: 415

How to convert an object into a map using Java-8

Consider following object:

class Interval {
   final String name;
   final Date start;
   final Date end;
   final int intervalId;
}

I am provided with a list of intervals. I need to check it equals a given map. eg:

boolean checkEqual(List<Interval> intervals, Map<Date, Date> startEnd) {


}
  1. I want to use Java8 to convert list of intervals into a map of start/end dates and then compare with startEndMap

i.e.

boolean checkEqual(List<Interval> intervals, Map<Date, Date> startEnd) {
       Map<Date, Date> map = intervals.streams.filter ?? is there a way to do it ?
       return map.equals(startEnd)
}

How to do it ?

  1. Is there a better way ?

Upvotes: 1

Views: 97

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56489

use the toMap collector:

Map<Date, Date> result = intervals.stream()
             .collect(Collectors.toMap(Interval::getStartDate, 
                             Interval::getEndDate));

Upvotes: 7

Related Questions