Hi guys, I'm a little stuck with something here.
Basically I have a a method which, given a List of Students will have to filter out those who are younger than 60yrs old and should return a List of Students who are over 60yrs old but I want this to be a list of Optionals rather than just a List of Students. THe difficulty is that I can't find a way to return a list of optionals like List<Optional>. I can return an optional if I use things like findFirst() or findAny()
return studentList.stream().filter(x -> x.getAge() > 60).findAny();
or i could return a simple list of students
return studentList.stream().filter(x -> x.getAge() > 60).collect(Collectors.toList());
but I want all the Students over 60 in a list of Optional.
Any idea how that can be done if it can be done that is?
Jump to Post
Something like this should give you enough info...
Stream<Integer> si = Stream.of(1, 2, 3, 4, 5); List<Optional<Integer>> result = si.filter(i -> i < 4). map(i -> Optional.of(i)). collect(Collectors.toList()); System.out.println(result);
Jump to Post
map(s -> Optional.of(s)) is transforming those objects into Optionals, correct?
Yes, but more accuratel:
.mapcreates a new Stream from the values returned by the lambda.
There are probably other ways to do it, but this is a really obvious and easy-to-read solution.
All 4 Replies
We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.