stream 常用方法
取 List arr 指定key 并用逗号隔开,外加 判断条件过滤
arr.filter(Objects::nonNull).stream().map(
entity->
entity.getCode() == 100 ? entity.key() "")
.filter(StringUtils::isNoneBlank).collect(Collectors.joining(",")
过滤掉 map value 为 空 or null 的属性
Map<String, Object> map1 = Optional.ofNullable(map).map(
(v) -> {
Map params = v.entrySet().stream()
.filter((e) -> (e.getValue()==null||e.getValue().equals("") ? false : true))
.collect(Collectors.toMap(
(e) -> (String) e.getKey(),
(e) -> e.getValue()
));
return params;
}
).orElse(null);
List 根据 指定字段 去重
List<NeusoftPatientInfo> newList = patientInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(NeusoftPatientInfo::getIdentityCard))), ArrayList::new));
List<Entity>
转 List<Map>
public Map<String, Object> toMap(NeusoftMedicineInfo medicineInfo) {
Map<String, Object> map = Maps.newHashMap();
map.put("beginTime", medicineInfo.getBeginTime());
map.put("identityCard", medicineInfo.getIdentityCard());
map.put("drugName", medicineInfo.getDrugName());
map.put("dosages", medicineInfo.getDosages());
map.put("unit", medicineInfo.getUnit());
map.put("dosagesSum", medicineInfo.getDosagesSum());
map.put("unitSum", medicineInfo.getUnitSum());
map.put("methods", medicineInfo.getMethods());
map.put("frequency", medicineInfo.getFrequency());
return map;
}
List<Map<String, Object>> collect = medicineInfos.stream()
.map(medicineInfo -> medicineInfo.toMap(medicineInfo))
.collect(Collectors.toList());
复杂例子 将list 按某一字段分组后,映射成指定map 类型
Map<String, Map<String, Object>> collect = list.stream()
.map(neusoftRecordsInfo -> neusoftRecordsInfo.toMap(neusoftRecordsInfo))
.filter(Objects::nonNull)
.collect(Collectors.groupingBy(
e -> e.get("id").toString()
, Collectors.toMap((e) -> e.keySet().stream().reduce((first, second) -> first).get(),
(f) -> f.entrySet().stream().reduce((first, second) -> first).get().getValue(), (v1, v2) -> v2)
));
public Map<String, Object> toMap(NeusoftRecordsInfo recordsInfo) {
Map<String, Object> map = Maps.newLinkedHashMap();
String c = recordsInfo.itemcode;
String r = recordsInfo.getResult();
if ("HGB".equals(c)) {
map.put("hemoglobin", r);
}
if ("WBC".equals(c)) {
map.put("leukocyte", r);
}
if ("PLT".equals(c)) {
map.put("platelet", r);
}
if (map.keySet().isEmpty()) {
return null;
}
map.put("id", recordsInfo.getBarcode());
return map;
复杂例子 将list 某些条件 分组,并排序,归纳子集 某一字段 组成list
Map<String, List<String>> collect = lists.stream().collect(
Collectors.groupingBy(
e -> StringUtils.substringBefore(e.getRecordDate(), " "),
TreeMap::new,
Collectors.mapping(MgDataEntity::getMachineBloodSugar, Collectors.toList())
));
分组,并排序,归纳子集 某一字段 取 entity
Map<Integer, IotDataFoundation> collect = iotDataFoundations.stream().filter(Objects::nonNull)
.collect(Collectors.toMap(IotDataFoundation::getMonType, Function.identity(), BinaryOperator.maxBy(Comparator.comparing(IotDataFoundation::getId))));