加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:37:32 所属栏目:Java 来源:网络整理
导读:Set ShipperModel shippers = baseSiteSerivce.getCurrentBaseSite().getStores().get(0).getShippers(); final ListKeyValueStoreModel kvList = keyValueStoreService.getKeyValueStoreModelListByCode(HERITAGEUNIT_DELIVERYINSTRUCTION_SHIPVIA);for (Sh
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.
        }
    }
}

我有两个项目列表,基于托运人我想要过滤kvlist
我想执行像kvlist.remainAll(shipper(基于代码))的操作,并希望将这些循环转换为流代码.

解决方法

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读