2 回答

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以使用collectingAndThen:
? ?myList.stream()
? ? ? ? ? ? .filter(item -> someMethod(item))
? ? ? ? ? ? .map(item -> doSomething(item))
? ? ? ? ? ? .collect(Collectors.collectingAndThen(Collectors.toList(), result -> {
? ? ? ? ? ? ? ? if (result.isEmpty()) throw new RuntimeException("Empty!!");
? ? ? ? ? ? ? ? return result;
? ? ? ? ? ? }));

TA貢獻(xiàn)2036條經(jīng)驗(yàn) 獲得超8個(gè)贊
由于沒有直接的方法如何檢查 Java 8 Stream 是否為空?,更好的代碼是:
List<SomeObject> output = myList.stream()
? ? ? ? .filter(item -> someMethod(item))
? ? ? ? .map(item -> doSomething(item))
? ? ? ? .collect(Collectors.toList());
if (!myList.isEmpty() && output.isEmpty()) {
? ? throw new RuntimeException("your message");
}?
另一種替代方法是使用noneMatch, 在執(zhí)行前進(jìn)行驗(yàn)證,例如:
if (myList.stream().noneMatch(item -> someMethod(item))) {
? ? throw new RuntimeException("your message");
}
添加回答
舉報(bào)