JDK1.8收集方法
根据集合某个字段求sum
IntSummaryStatistics caramsCollect = caramsList.stream().collect(Collectors.summarizingInt(map ->
Integer.parseInt(StringTool.toString(map.get("count")))));
计算 数量
int sum = appleList.stream().mapToInt(Apple::getNum).sum();
//计算 总金额
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
分组求和
Map<String, LongSummaryStatistics> sum = caramsList.stream().collect(
Collectors.groupingBy(ReportMonthBasicResourceData::getInsertMonth,
Collectors.summarizingLong(ReportMonthBasicResourceData::getInsertCount)));
条件求个数
long count = list.stream().filter(person -> (person.getAge() > 19)).count();
根据某个字段得到新的集合
List<Document> thrList = list.stream().filter(data -> !StringTool.toString(data.get("eventType")).equals(SnapAlarmConstant.SMSR_ALARM_FACE)).collect(Collectors.toList());
根据逗号拼接
String typeStr = typeList.stream().map(str->"'"+str+"'").collect(Collectors.joining(","));
根据某个字段分组
Map<String, Long> sum = cars.stream().collect(
Collectors.groupingBy(Car::getName, Collectors.counting()));
集合操作成map
Map<String, Long> dataMap = faceList.stream()
.collect(Collectors.toMap(alarmMap -> StringTool.toString(alarmMap.get("date")), alarmMap -> Long.parseLong(StringTool.toString(alarmMap.get("count")))));
去重
List<Map<String,Object>> devicePersonList = deviceList.stream().distinct().collect(Collectors.toList());
根据某个字段去重
List<PersonnelControlVo> distinctPersonInfos =personInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(PersonnelControlVo :: getFaceId))), ArrayList::new));
得到某个字段的集合,再根据条件筛选
List<List<Double>> featureList = pictures.stream().map(Picture::getFeatures).filter(item -> !CollectionUtils.isEmpty(item)).collect(Collectors.toList());
排序
resultList.sort(Comparator.comparing(AirportChannelVo::getId).reversed());
集合根据某个字段去重
List<PersonnelControlVo> objRelationList = personInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(PersonnelControlVo::getFaceId))), ArrayList::new));
集合转数组
方式一:
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
String[] strings = list.stream().toArray(String[]::new);
方式二、
List<String> list2 = new ArrayList<>();
list2.add("a");
list2.add("b");
list2.add("c");
String[] strin = list2.toArray(new String[list2.size()]);
map转list 并且排序
List<ComprehensiveDeviceVo> resultDataList = dataMap.entrySet().stream()
.map(e -> ComprehensiveDeviceVo.builder().count(e.getValue()).deviceId(e.getKey()).build())
.sorted(Comparator.comparing(ComprehensiveDeviceVo::getCount).reversed())
.collect(Collectors.toList());
流式处理分割集合
//方法二:获取分割后的集合
List<List<Integer>> splitList = Stream.iterate(0, n -> n + 1).limit(limit).parallel().map(a -> list.stream().skip(a * MAX_NUMBER).limit(MAX_NUMBER).parallel().collect(Collectors.toList())).collect(Collectors.toList());