[英]How to compare two arrayList's objects elements in java 8
我正在嘗試比較一個 arrayList object 元素包含另一個 arraylist 和下面的代碼,但這不能像我預期的那樣工作
arrayList1=[{productSku:"123"},{productSku:"1234"}]
arrayList2=[{productSku:"123"},{productSku:"1000"}]
我的情況是,如果 arraylist1 元素與 arraylist2 中的任何元素都不匹配,那么我們應該拋出異常
arrayList2.stream().filter(type -> "EQUIPMENT".equals(type.getItemType()))
.forEach(action -> {
arrayList1.forEach(action1 -> {
if (!action1.getProductSku().equalsIgnoreCase(action.getProductSKU())) {
// Throw exception
}
});
});
雖然 Deadpool 的回答很棒,但我更傾向於避免在這里使用Optional
,因為要使用的實際值沒有用處。
此外,為遍歷Stream
的每個元素創建Stream
在性能方面並不是一個好主意。
Set<String> products = arrayList1.stream()
.map(Action::getProductSku)
.map(String::toUpperCase)
.collect(toSet());
boolean shouldThrowAnException = arrayList2.stream()
.filter(type -> "EQUIPMENT".equals(type.getItemType()))
.map(Action::getProductSku)
.map(String::toUpperCase)
.noneMatch(products::contains);
if (shouldThrowAnException) {
// throw exception
}
您可以 stream arrayList2
並嘗試使用findFirst在arrayList1
中找到至少一個匹配元素,否則拋出異常
arrayList2.stream()
.filter(type -> "EQUIPMENT".equals(type.getItemType()))
.filter(list2-> arrayList1.stream()
.anyMatch(list1->list1.getProductSku().equals(list2.getProductSku())))
.findFirst()
.orElseThrow(//some exception)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.