有没有更好的方法来过滤/映射下面:
list.stream()
.filter(o -> !(o instanceof Person))
.findAny()
.ifPresent(o -> { throw new RuntimeException(); });
list.stream()
.filter(o -> o instanceof Person)
.map(o -> o.getName())
.toList();
我想处理列表中作为类实例的所有元素,例如
Person
,如果任何元素不是 Person
的实例,那么我想抛出异常。想知道是否有某种方法可以组合上述语句,这样我就不需要两次流式传输列表?
你可以试试这个
list.stream()
.peek(o -> {
if (! (o instanceof Person)) throw new RuntimeException();
})
.map(o -> ((Person) o).getName())
.collect(Collectors.toList());