目录
1.9通过summarizingInt同时求总和、平均值、最大值、最小值
1.stream流常用方法
1.1filter筛选
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().filter(i -> i > 3);
1.2distinct去除重复元素
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().distinct();
1.3 limit返回指定流个数
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().limit(3);
1.4 skip跳过流中的元素
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().skip(2);
1.5 元素匹配
1. allMatch匹配所有
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().allMatch(i -> i > 3)) {
System.out.println("值都大于3");
}
2.anyMatch匹配其中一个
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().anyMatch(i -> i > 3)) {
System.out.println("存在大于3的值");
}
3.noneMatch全部不匹配
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().noneMatch(i -> i > 3)) {
System.out.println("值都小于3");
}
1.6获取最大最小值
Optional<Integer> min = menu.stream().map(Dish::getCalories).min(Integer::compareTo);
Optional<Integer> max = menu.stream().map(Dish::getCalories).max(Integer::compareTo);
1.7 求和
int sum = menu.stream().mapToInt(Dish::getCalories).sum();
1.8 平均值
double average = menu.stream().collect(averagingInt(Dish::getCalories));
1.9通过summarizingInt同时求总和、平均值、最大值、最小值
IntSummaryStatistics intSummaryStatistics = menu.stream().collect(summarizingInt(Dish::getCalories));
double average = intSummaryStatistics.getAverage(); //获取平均值
int min = intSummaryStatistics.getMin(); //获取最小值
int max = intSummaryStatistics.getMax(); //获取最大值
long sum = intSummaryStatistics.getSum(); //获取总和
2.0 逗号分割转成list,list字符串转成逗号分割
System.out.println("---------list遍历后以“,”分隔(流模式)----------");
String collect2 = asList.stream().collect(Collectors.joining(","));
System.out.println("---------根据某个字段进行拼接----------");
String names = itemResponse.getDevices().stream().map(Device::getName).collect(Collectors.joining(","));
System.out.println("--------字符串以“,”切分(流处理)---------");
List<String> collect = Stream.of(string.split(",")).collect(Collectors.toList());
2.1 进阶通过groupingBy进行分组
Map<Type, List<Dish>> result = dishList.stream().collect(Collectors.groupingBy(Dish::getType));
2.2 根据日期字段进行排序
// reversed为倒序,不加则正序
approvalRecords.stream().
sorted(Comparator.comparing(ReportApprovalRecordResponse::getUpdateDate)).collect(Collectors.toList());
2.3 根据一个或多个条件过滤
templateChildItems.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(p -> p.getTemplateId() + ";" + p.getItemChildId()))), ArrayList::new));