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字段。
通过使用流,可以更加高效地处理大量数据,并且代码更简洁易读。