Reputation: 4232
I am trying to compare one arrayList object elements contains another arraylist with below code but this is not working as i expected can some one help me please
arrayList1=[{productSku:"123"},{productSku:"1234"}]
arrayList2=[{productSku:"123"},{productSku:"1000"}]
My scenario is if arraylist1 elements not matching with any of the element in arraylist2 then we should throw exception
arrayList2.stream().filter(type -> "EQUIPMENT".equals(type.getItemType()))
.forEach(action -> {
arrayList1.forEach(action1 -> {
if (!action1.getProductSku().equalsIgnoreCase(action.getProductSKU())) {
// Throw exception
}
});
});
Upvotes: 0
Views: 1235
Reputation: 21975
While Deadpool's answer is great, I'd be more inclined to avoid using Optional
here, as there is no use for the actual value to be used.
Also, creating a Stream
for each element traversing the Stream
is not a good idea in terms of performance.
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
}
Upvotes: 2
Reputation: 40048
You can stream the arrayList2
and try finding at least one matching element in arrayList1
using findFirst or else throw exception
arrayList2.stream()
.filter(type -> "EQUIPMENT".equals(type.getItemType()))
.filter(list2-> arrayList1.stream()
.anyMatch(list1->list1.getProductSku().equals(list2.getProductSku())))
.findFirst()
.orElseThrow(//some exception)
Upvotes: 1