I have 2 variable (day and time) and 2 lists of objects (list1 and list2);
ArrayList<Teacher> list1 = new Teacher<>();
list1.add(new Teacher(1, "Mary")); //Tid, name
list1.add(new Teacher(2, "Anne"));
....
ArrayList<Session> list2 = new Session<>();
list2.add(new Session(101, 1, "Monday", "2-4pm")); //Sid, Tid, day, time
list2.add(new Session(102, 1, "Tuesday", "2-4pm"));
list2.add(new Session(103, 2, "Monday", "9-11pm"));
....
String day = "Monday"
String time = "9-11am"
I want to check if all the teachers have classes on monday from 9-11am using the Tid and the given day and time)
This is what I tried - using streams
Predicate<Session> dayEquals = s -> s.getDay().equals(day);
Predicate<Session> timeEquals = s -> s.getTime().equals(time);
Predicate<Session> combinedCondition = dayEquals.and(timeEquals);
if (list2.stream().filter(s -> s.getTid() == t -> t.getTid).anyMatch(combinedCondition)) {
System.out.println("All teachers are occupied");
}
Thanks!
CodePudding user response:
You can use java stream API for this task. Assuming you have appropriate getters in your Teacher
and Session
class. I don't understand your approach as the combinedCondition
is missing but whatever it may be anyMatch
shouldn't be used if the condition checks for all teachers of list 1
to be present as per your question. You should use allMatch
that checks if all the elements of list 1
match the given predicate.
// get all the teachers' id as set who have session on given day and time
Set<Integer> tidList =list2.stream()
.filter(session -> (day.equals(session.day)
&& time.equals(session.time)))
.map(Session::getTid)
.collect(Collectors.toSet());
// check if all the teachers from list1 is in the above set.
boolean result = list1.stream()
.map(Teacher::getId)
.allMatch(tidList::contains);