List<EquipmentDeviceMessage> equipmentDeviceMessageInfo = greenThinkTanksInfoPlanMapper.getEquipmentDeviceMessageInfo(phone, startDate, endDate);
List<BladeUserVo> userList = bladexsqlMapper.getUserList();
Q
:上面两个列表怎么使用流,根据equipmentDeviceMessageInfo中的phone字段去匹配userList 中的phone字段再获取userList 中是name赋值给equipmentDeviceMessageInfo 中的name。A
:以前的写法是通过for循环遍历一个一个去查询赋值,这样的话如果数据多的话一个一个遍历会查询的话肯定是很慢的,下面的方法是通过List中的stream流去匹配并赋值。
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
List<EquipmentDeviceMessage> equipmentDeviceMessageInfo = greenThinkTanksInfoPlanMapper.getEquipmentDeviceMessageInfo(phone, startDate, endDate);
List<BladeUserVo> userList = bladexsqlMapper.getUserList();
// 将userList转换为Map,以phone为键,name为值
Map<String, String> userMap = userList.stream()
.collect(Collectors.toMap(BladeUserVo::getPhone, BladeUserVo::getName));
// 遍历equipmentDeviceMessageInfo,根据phone匹配userMap,将name赋值给equipmentDeviceMessageInfo中的name字段
equipmentDeviceMessageInfo.forEach(equipment -> {
String phone = equipment.getPhone();
if (userMap.containsKey(phone)) {
equipment.setName(userMap.get(phone));
}
});
}
}
首先使用流将userList转换为一个Map,以phone作为键,name作为值。接着,使用forEach方法遍历equipmentDeviceMessageInfo列表,根据phone匹配userMap,如果找到匹配项,则将对应的name赋值给equipmentDeviceMessageInfo中的name字段。文章来源:https://www.toymoban.com/news/detail-723559.html
通过使用流,可以更加高效地处理大量数据,并且代码更简洁易读。文章来源地址https://www.toymoban.com/news/detail-723559.html
到了这里,关于Java中通过List中的stream流去匹配相同的字段去赋值,避免for循环去查询数据库进行赋值操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!