如何更简洁高效地实现双列表匹配并设置User对象的Billing字段?
优化用户列表字段赋值逻辑
现有两个列表:
List<User> userList = ... List<Long> userIdWithBilling = ...
需求:若userList中User对象的userId存在于userIdWithBilling列表中,将该User的billing字段设为true。
原实现代码如下:
for(Long userId : userIdWithBilling){ Optional<User> optUserList = userList.stream() .filter(ul->ul.getUserId().longValue()==userId) .findFirst(); if(optUserList.isPresent()){ optUserList.get().setBilling(true); } }
优化方案
原逻辑的问题在于每次循环都要遍历整个userList查找匹配用户,时间复杂度为O(n*m),效率偏低。以下是更简洁高效的实现:
高效版(推荐)
先将userIdWithBilling转为HashSet(查找时间复杂度O(1)),再遍历userList设置字段:
Set<Long> billingUserIdSet = new HashSet<>(userIdWithBilling); userList.forEach(user -> user.setBilling(billingUserIdSet.contains(user.getUserId())));
整个逻辑的时间复杂度降为O(n+m),大幅提升效率。
一行代码版
如果追求代码精简,可将集合创建直接嵌入操作:
userList.forEach(user -> user.setBilling(new HashSet<>(userIdWithBilling).contains(user.getUserId())));
注意:若userList数据量较大,不推荐此写法,因为每次遍历都会创建新的HashSet,会额外消耗资源。
内容的提问来源于stack exchange,提问作者robert trudel
相关产品推荐
相关产品推荐

