【JAVA学习】List stream流使用实例
List stream流使用实例
根据某个字段分类查询数量
Map<Integer, Long> map = list.stream().collect(Collectors.groupingBy(RobotDevice::getDeviceStatus, Collectors.counting()));
在实体类list筛选出userid的list
Set<Long> userIdList = list.stream().map(ProjectTeamUser::getUserId).collect(Collectors.toSet());
生成string类型的userId的list数据
Set<String> userIdListString = userIdList.stream().map(String::valueOf).collect(Collectors.toSet());
根据userIdList 筛选出list中 满足的数据
List<SafetyStarRecord> collect1 = list.stream()
.filter(s -> userIdListString.contains(s.getBeLookerId()))
.collect(Collectors.toList());
根据 DeviceRDHelmetPojo::getDataType 字段给 list数据进行分组
Map<Integer, List<DeviceRDHelmetPojo>> groupedByDataType = list.stream()
.collect(Collectors.groupingBy(DeviceRDHelmetPojo::getDataType));
//
for (Map.Entry<Integer, List<DeviceRDHelmetPojo>> entry : groupedByDataType.entrySet()) {
Integer key = entry.getKey();
List<DeviceRDHelmetPojo> value = entry.getValue();
}
根据 字段获取 数据 可能会有多条,如果有多条的话 就拿最后一个
Optional<ScDeviceType> first= list.stream().filter(s -> Objects.equals(s.getId(), r.getDeviceTypeId())).findFirst();
ScDeviceType scDeviceType = new ScDeviceType();
if (first.isPresent()) {
scDeviceType = first.get();
}
根据 字段 获取 数据 可能会有多条,如果有多条的话 就拿最后一个 代码实例
List<ProjectManagementInspection> collect = list.stream()
.filter(p -> Objects.equals(p.getPmId(), item.getPmId()))
.filter(p -> Objects.equals(p.getItemId(),Integer.valueOf(item.getItemId()) ))
.collect(Collectors.toList());
ProjectManagementInspection one = collect.isEmpty() ? null : collect.get(collect.size() - 1);