第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如果過濾器返回大小為 0 的列表,則拋出異常

如果過濾器返回大小為 0 的列表,則拋出異常

猛跑小豬 2023-08-23 17:06:38
在下面的代碼中:myList.stream()     .filter(item -> someMethod(item))     .map(item -> doSomething(item))     .collect(Collectors.toList());RuntimeException如果過濾器的結(jié)果是大小為 0 的列表(即沒有項(xiàng)目通過過濾器),我該如何拋出 a ?
查看完整描述

2 回答

?
aluckdog

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;

? ? ? ? ? ? }));


查看完整回答
反對(duì) 回復(fù) 2023-08-23
?
慕桂英3389331

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");

}


查看完整回答
反對(duì) 回復(fù) 2023-08-23
  • 2 回答
  • 0 關(guān)注
  • 184 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)