Trying to map a set of indices to their corresponding object in a list, then return as a set.
List aList = Arrays.asList(new Object(), new Object(), new Object(), new Object(), new Object(), new Object());
Set.of(0, 2, 3)
.stream()
.flatMap(index -> aList.get(index)) // error on this line
.collect(Collectors.toSet());
Error message: no instance(s) of type variable(s) R exist so that Object conforms to Stream<? extends R>
You need map
in this example, not flatMap
. flatMap
is used when each element of the original Stream
is mapped to multiple elements.
Set.of(0, 2, 3)
.stream()
.map(index -> aList.get(index))
.collect(Collectors.toSet());
EDIT: your updated question makes my alternative suggestions obsolete, but the remaining snippet still works.
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.