简体   繁体   中英

How do I filter using streams a set of objects based on criteria for a Map field?

I have an ArrayList of Event objects, one of whose fields is Map<LocalDateTime, Auditorium> schedule - representing a schedule of the event, ie when and in which auditoriums it airs. The implementation of Auditorium is not important for the sake of the question. I want to get a list of events airing between certain dates / times. I wrote a method that was expected to look through the set of the air dates of each event and filter only those events for which at least one air date is within the given timeframe:

public List<Event> getForDateRange(LocalDateTime from, LocalDateTime to) {
    events.stream()
          .filter(s -> s.getSchedule()
              .keySet()
              .stream()
              .anyMatch(t -> t.compareTo(from) >= 0 && t.compareTo(to) <= 0))
          .collect(Collectors.toList());
}

I am then trying to test the method as follows:

List<Event> events = new ArrayList<>();
Map<LocalDateTime, Auditorium> schedule = new HashMap<>();

schedule.put(LocalDateTime.of(2019, 4, 20, 18, 30), auditorium);
schedule.put(LocalDateTime.of(2019, 4, 20, 19, 30), auditorium);
schedule.put(LocalDateTime.of(2019, 4, 20, 20, 30), auditorium);
schedule.put(LocalDateTime.of(2019, 4, 20, 21, 30), auditorium);
Event event1 = new Event("Show1", schedule);
events.add(event1);
schedule.clear();

schedule.put(LocalDateTime.of(2019, 4, 20, 16, 30), auditorium);
schedule.put(LocalDateTime.of(2019, 4, 20, 17, 30), auditorium);
Event event2 = new Event("Show2", schedule);
events.add(event2);
schedule.clear();

LocalDateTime from = LocalDateTime.of(2000, 1, 1, 0, 0);
LocalDateTime to = LocalDateTime.of(2019, 4, 20, 20, 40);

List<Event> result = getForDateRange(from, to);

I expected result to contain both event1 and event2 , however it's an empty list. What is wrong with the method's logic?

Thanks.

Unless you are making a copy of your map when you create an event, your event schedules will be empty. When you clear the schedule you are clearing the schedules from the events that you just added to the event list? So when you try to compare events, both schedules in the list of events are empty.

This is because each event contains the same reference to the same map and you clear them both.

You need to declare a new map for each schedule and don't clear anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM