How to replace two loops with a stream and keep the same elements in the list
•
Java
Set <ShipperModel> shippers = baseSiteSerivce.getCurrentBaseSite().getStores().get(0).getShippers();
Set <ShipperModel> shippers = baseSiteSerivce.getCurrentBaseSite().getStores().get(0).getShippers();
final List<KeyValueStoreModel> kvList = keyValueStoreService.getKeyValueStoreModelListByCode(HERITAGEUNIT_DELIVERYINSTRUCTION_SHIPVIA);
for (ShipperModel shipperModel : shippers)
{
for (KeyValueStoreModel keyValueStoreModel : kvList)
{
if(shipperModel.getCode().equals(keyValueStoreModel.getCode()))
{
// if codes are equals then it will remain in the kvList.
}
}
}
I have two item lists, based on the shipper, I want to filter kvlist, and I want to execute like kvlist Remainall (shipper) and want to convert these loops into stream code
Solution
Not ideal, but you can try something similar:
List<KeyValueStoreModel> filtered = kvlist.stream().filter(
kv -> shippers.stream().anyMatch(
s -> s.getCode().equals(kv.getCode())
)
)
).collect(Collectors.toList());
So we get a stream of kV elements instead of checking whether there are any corresponding elements in the shipper set. Finally, we collect the matching elements into a new list
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
