如何使用流替换两个循环并保留列表中相同的元素

Dev*_*dra 3 java collections java-8 java-stream

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.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我有两个项目列表,并根据托运人我想过滤kvlist我想执行操作kvlist.remainAll(shipper(based on code)),并希望将这些循环转换为流代码.

Ant*_*iuc 5

不理想,但你可以尝试做类似的事情:

List<KeyValueStoreModel> filtered = kvlist.stream().filter(
      kv -> shippers.stream().anyMatch(
               s -> s.getCode().equals(kv.getCode())
            )
      )
).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

所以我们得到了一个Streamkv元素,而不是检查托运人是否有任何相应的元素Set,最后我们将匹配的元素收集到一个新元素中List.