用流操作集合常用方法: 用指定字段做为分组条件: Map<String, List<JSONObject>> inherentMap = inherentList.stream().collect(Collectors.groupingBy(o -> o.getString("ins_code"))); 用指定字段分组并保持数据原有排序 LinkedHashMap<String, List<JSONObject>> dataLinkedList = list.stream().collect(Collectors.groupingBy(o -> o.getString("devCode"), LinkedHashMap::new, Collectors.toList())); 将指定字段排序 dataList.sort(Comparator.comparing(o -> o.getString("gatherTime"))); alarmRecoredList.sort(Comparator.comparing((Map<String, Object> o) -> String.valueOf(getMapValue(o, "createTime")))); alarmRecoredList.sort(Comparator.comparing((Map<String, Object> o) -> String.valueOf(getMapValue(o, "createTime"))).reversed()); 将某值映射成另一个值并求和或收集 double predictFee = yearEnergyList.stream().mapToDouble(s -> Double.parseDouble(s.getPredictFee())).sum(); 将值映射去重并收集 List<String> propTypeList = jsonObjectList.stream().map(e -> e.getString("propType")).distinct().collect(Collectors.toList()); 对集合进行过滤并对指定字段值进行排序,收集结果值 List<JSONObject> collect = lst.stream().filter(o -> o.getString("propCode").equals(propCode)).sorted(Comparator.comparing(ob -> ob.getString("createTime"))).collect(Collectors.toList()); 将集合元素取出装入map Map<Integer, String> result3 = list.stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getName())); Map<String, Long> result1 = list.stream().collect(Collectors.toMap(Hosting::getName, Hosting::getWebsites)); 先排序再收集 Map<String, Long> result = list.stream().sorted(Comparator.comparingLong(Hosting::getWebsites).reversed()) .collect(Collectors.toMap(Hosting::getName,Hosting::getWebsites,(oldValue, newValue) -> oldValue, LinkedHashMap::new)); 将对象中某字段作为key,整体作为value Map<String, JSONObject> dataMap = energyDosageMonthBySysIns.stream() .filter(o -> StringUtils.isNotBlank(o.getString("deviceId"))) .collect(Collectors.toMap(item -> item.getString("deviceId"), Function.identity()));
Stream流的常用操作
于 2022-02-22 08:47:11 首次发布