栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JDK8StreamApi

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JDK8StreamApi

文章目录
  • 方法函数
  • 使用
    • 前提
    • foreach
    • find
    • match
    • filter
    • max
    • min
    • count
    • map
    • reduce
    • collect
    • partitioningBy(groupingBy)
    • joining
    • sorted
    • 提取/组合
    • 差集

方法函数
方法名字说明
foreach循环
findfindFirst():返回第一个元素,findAny():返回任意一个元素
matchanyMatch() :满足一个为true; allMatch():全部满足为true
filter按照过滤
max最大
min最小
count计算个数
map接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
flatMap接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
reduce把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作
collect1.计数: count :2:平均值: averagingInt、 averagingLong、 averagingDouble;3.最值: maxBy、 minBy;4.求和: summingInt、 summingLong、 summingDouble;5.统计以上所有: summarizingInt、 summarizingLong、 summarizingDouble
partitioningBy/groupingBy分组·
joining将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。
sorted排序
提取/组合流也可以进行合并、去重、限制、跳过等操作。
差集
使用 前提

1.new Person

@Data
public class Person {
    private String name;
    private int age;
    private int salary;//工资

    public Person(String name, int age, int salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + ''' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}

2.创建person集合

List personList = new ArrayList<>();
personList.add(new Person("张三", 20, 5000));
personList.add(new Person("李四", 30, 6000));
personList.add(new Person("王五", 40, 7000));
personList.add(new Person("赵六", 50, 8000));
personList.add(new Person("田七", 60, 9000));

foreach
 personList.forEach(System.out::println);
find
// 获取满足(Stream)任意一个值 如:满足员工年大于40 
Optional findAny= personList.stream().filter(p -> p.getAge() > 40).findAny(); 
System.out.println(findAny.get());//结果:[Person{name='赵六', age=50, salary=8000}]
// 满足(Stream)第一个值 如:满足员工年大于40 
Optional findFirst= personList.stream().filter(p -> p.getAge() > 40).findFirst();
System.out.println(findFirst.get());//结果:[Person{name='赵六', age=50, salary=8000}]
match
 //判断 员工集合是否全部都大于40岁
boolean allMatch = personList.stream().allMatch(person -> person.getAge() > 40);
System.out.println("allMatch = " + allMatch);//结果:false
// 判断 员工集合是否有一个大于40岁
boolean anyMatch = personList.stream().anyMatch(person -> person.getAge() > 40);
System.out.println("anyMatch = " + anyMatch);//结果:true

filter
//查找年龄大于40的人 并且保存成新集合
List personList40 = personList.stream().filter(p -> p.getAge() > 40).collect(Collectors.toList());
System.out.println("personList40 = " + personList40);//结果:[Person{name='赵六', age=50, salary=8000}, Person{name='田七', age=60, salary=9000}]
max
//查询工资最大的人
Comparator comparator = Comparator.comparing(Person::getSalary);//按照工资排序
Optional person = personList.stream().max(comparator);
System.out.println("person = " + person.get());//结果:Person{name='田七', age=60, salary=9000}
min
  //查询年龄最小的人
Comparator anInt = Comparator.comparingInt(Person::getAge);//按照年龄排序
Optional person = personList.stream().min(anInt);
System.out.println("person = " + person.get());//结果:Person{name='张三', age=20, salary=5000}
count
//计算年龄大于40的人数量
long count = personList.stream().filter(p -> p.getAge() > 40).count();
System.out.println("count = " + count);//结果:2
map
  // 对所有员工进行涨薪500元
 List list = personList.stream().map(person -> {
        person.setSalary(String.valueOf(Integer.parseInt(person.getSalary()) + 500));
        return person;
    }).collect(Collectors.toList());
    System.out.println("list = " + list);//结果:[Person{name='张三', age=20, salary=5500}, Person{name='李四', age=30, salary=6500}, Person{name='王五', age=40, salary=7500}, Person{name='赵六', age=50, salary=8500}, Person{name='田七', age=60, salary=9500}]

reduce
  //reduce :求和,求最值,求乘积
//1.求员工工资总和
 Optional reduce = personList.stream().map(person -> Integer.parseInt(person.getSalary())).reduce(Integer::sum);
 System.out.println("reduce = " + reduce.get());//结果:35000
 //2.求员工工资最大值
 Optional reduce1 = personList.stream().map(person -> Integer.parseInt(person.getSalary())).reduce(Integer::max);
 System.out.println("reduce1 = " + reduce1.get());//结果:9000
 //3.求员工年龄最小值
 Optional reduce2 = personList.stream().map(Person::getAge).reduce(Integer::min);
 System.out.println("reduce2 = " + reduce2.get());//结果:20
 //4.求员工工资乘积
 Optional reduce3 = personList.stream().map(Person::getAge).reduce((a, b) -> a * b);
 System.out.println("reduce3 = " + reduce3);// 结果:72000000
collect
//1.统计员工人数
long count = personList.stream().count();
System.out.println("count = " + count); //结果:5
Long collect = personList.stream().collect(Collectors.counting());
System.out.println("collect = " + collect); //结果:5
//2.求平均年龄
Double aDouble = personList.stream().collect(Collectors.averagingInt(Person::getAge));
System.out.println("aDouble = " + aDouble);//结果:40.0
Double aDouble1 = personList.stream().collect(Collectors.averagingInt(p -> p.getAge()));
System.out.println("aDouble1 = " + aDouble1);//结果:40.0
//3.求最高年龄
Optional maxBy = personList.stream().map(Person::getAge).collect(Collectors.maxBy(Integer::compare));
System.out.println("maxBy = " + maxBy.get());//结果:60
//4.求最低年龄
Optional minBy = personList.stream().map(Person::getAge).collect(Collectors.minBy(Integer::compare));
System.out.println("minBy = " + minBy.get());//结果:20
//5.求年龄总和
Integer summingInt = personList.stream().collect(Collectors.summingInt(Person::getAge));
System.out.println("summingInt = " + summingInt);//结果:200
//6统计以上员年龄信息
IntSummaryStatistics summarizingInt = personList.stream().collect(Collectors.summarizingInt(Person::getAge));
System.out.println("summarizingInt = " + summarizingInt);//结果:IntSummaryStatistics{count=5, sum=200, min=20, average=40.0, max=60}

partitioningBy(groupingBy)
// 将员工按年龄高于40分为两部分
Map> booleanListMap = personList.stream().collect(Collectors.partitioningBy(person -> person.getAge() > 40));
System.out.println("booleanListMap = " + booleanListMap);//{false=[Person{name='张三', age=20, salary=5000}, Person{name='李四', age=30, salary=6000}, Person{name='王五', age=40, salary=7000}], true=[Person{name='赵六', age=50, salary=8000}, Person{name='田七', age=60, salary=9000}]}
Map> booleanListMap1 = personList.stream().collect(Collectors.groupingBy(person -> person.getAge() > 40));
System.out.println("booleanListMap1 = " + booleanListMap1);//{false=[Person{name='张三', age=20, salary=5000}, Person{name='李四', age=30, salary=6000}, Person{name='王五', age=40, salary=7000}], true=[Person{name='赵六', age=50, salary=8000}, Person{name='田七', age=60, salary=9000}]}
        
joining
//将员工的名字拼接起来
String collect = personList.stream().map(Person::getName).collect(Collectors.joining(","));
System.out.println("collect = " + collect);//结果:张三,李四,王五,赵六,田七
sorted
//将员工按照年龄排序
List collect = personList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
System.out.println("collect = " + collect);//结果:[Person{name='张三', age=20, salary=5000}, Person{name='李四', age=30, salary=6000}, Person{name='王五', age=40, salary=7000}, Person{name='赵六', age=50, salary=8000}, Person{name='田七', age=60, salary=9000}]

提取/组合
String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "d", "e", "f", "g" };
Stream stream1 = Stream.of(arr1);
Stream stream2 = Stream.of(arr2);
// concat:合并两个流 distinct:去重
List newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
// limit:限制从流中获得前n个数据
List collect = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
// skip:跳过前n个数据
List collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());

System.out.println("流合并:" + newList);//[a, b, c, d, e, f, g]
System.out.println("limit:" + collect);//[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
System.out.println("skip:" + collect2);//[3, 5, 7, 9, 11]
差集
//计算两个list中的差集
List reduce1 = allList.stream().filter(item -> !wList.contains(item)).collect(Collectors.toList());
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/926607.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号