(三)流的终止操作

终止操作

流方法含义
anyMatch检查是否至少匹配一个元素,返回boolean。
allMatch检查是否匹配所有元素,返回boolean。
noneMatch检查是否没有匹配所有元素,返回boolean。
findAny将返回当前流中的任意元素。
findFirst返回第一个元素
forEach遍历流
collect收集器,将流转换为其他形式。
reduce可以将流中元素反复结合起来,得到一个值。
max/min/count返回流中元素最大/最小/总数。
1. 收集(collect)

1.1归集(toList/toSet/toMap)

转化成新的List
List<> new = old.stream().collect(Collectors.toList());

转化成Map
Map<T,E> new= old.stream().collect(Collectors.toMap(T,E));

转换成set集合
Set<> new =old.stream().Collectors.toSet();

转换成特定的set集合
TreeSet<> new =old.stream().Collectors.toCollection(TreeSet::new);

转化成新的List

原始data:
List<User> userList = new ArrayList<>();
userList.add(new User(1, "张三", 18));
userList.add(new User(2, "李四", 19));
userList.add(new User(3, "王五", 20));

//user的id提取出来
List<User> users = userList;
List<Integer> idList = users.stream().map(User::getId).collect(Collectors.toList());
//{1, 2, 3}
System.out.println(idList);

转化成Map

/1.两个参数的用法
//将userList转化为key为id,value为User对象的map
Map<Integer, User> map1 = userList.stream().collect(Collectors.toMap(User::getId, p -> p));
Map<Integer, User> map2 = userList.stream().collect(Collectors.toMap(User::getId, p -> p));

//结果
{
    1: User(1, "张三", 18)
    2: User(2, "李四", 19)
    3: User(3, "王五", 20)
}

//2.三个参数的用法
Map<Integer, String> map3 = userList.stream().collect(Collectors.toMap(User::getAge, User::getName, (a, b) -> b));

//结果
{
    19: "李四"
    20: "王五"
}

//Collectors.groupingBy()
//当你想获取key是age的map,又不想覆盖掉重复项数据
Map<Integer, List<User>> map4 = userList.stream().collect(Collectors.groupingBy(User::getAge));
System.out.println(map4);

//结果
{
    18: [User(1, "张三", 18)]
    19: [User(2, "李四", 19)]
    20: [User(2, "王五", 20)]
}

1.2 统计(count/averaging)

Collectors提供了一系列用于数据统计的静态方法:

  • 计数:count
  • 平均值:averagingInt、averagingLong、averagingDouble
  • 最值:maxBy、minBy
  • 求和:summingInt、summingLong、summingDouble
  • 统计以上所有:summarizingInt、summarizingLong、summarizingDouble
public static void main(String[] args) {
    List<Person> personList = new ArrayList<Person>();
    personList.add(new Person(1, "zhangsan", 18, 4000, "shanghai"));
    personList.add(new Person(2, "lisi", 19, 5000, "beijing"));
    personList.add(new Person(3, "wanger", 20, 6000, "guangdong"));
    personList.add(new Person(4, "mazi", 21, 7000, "jiangxi"));
    personList.add(new Person(5, "laoer", 22, 8000, "zhejiang"));

    // 求总数
    Long count = personList.stream().collect(Collectors.counting());
    // 求平均工资
    Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
    // 求最高工资
    Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
    // 求工资之和
    Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
    // 一次性统计所有信息
    DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));

    System.out.println("员工总数:" + count);
    System.out.println("员工平均工资:" + average);
    System.out.println("员工工资总和:" + sum);
    System.out.println("员工工资所有统计:" + collect);

}

//结果
员工总数:5
员工平均工资:6000.0
员工工资总和:30000
员工工资所有统计:DoubleSummaryStatistics{count=5, sum=30000.000000, min=4000.000000, average=6000.000000, max=8000.000000}

1.3 归约(reducing)
Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持。

public static void main(String[] args) {
    List<Person> personList = new ArrayList<Person>();
    personList.add(new Person(1, "zhangsan", 18, 4000, "shanghai", "男"));
    personList.add(new Person(2, "lisi", 19, 5000, "beijing", "女"));
    personList.add(new Person(3, "wanger", 20, 6000, "guangdong", "男"));
    personList.add(new Person(4, "mazi", 21, 7000, "jiangxi", "男"));
    personList.add(new Person(5, "laoer", 22, 8000, "zhejiang", "女"));

    Integer allAge = personList.stream().map(Person::getAge).collect(Collectors.reducing(Integer::sum)).get();
    System.out.println(allAge);
}  

//结果
100



容器x = list.stream().reduce(最终返回的容器x, (容器x, 元素y) -> {
            容器x与元素y之间的逻辑操作;
            return 容器x;
        }, (x, y) -> {
            并行的时候才会执行;
            x和y是每个线程的返回的容器x;
            这里进行各个容器的累计操作;
            return x;
        });

1.4 接合(joining)
joining可以将 stream 中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。

public static void main(String[] args) {
    List<Person> personList = new ArrayList<Person>();
    personList.add(new Person(1, "zhangsan", 18, 4000, "shanghai", "男"));
    personList.add(new Person(2, "lisi", 19, 5000, "beijing", "女"));
    personList.add(new Person(3, "wanger", 20, 6000, "guangdong", "男"));
    personList.add(new Person(4, "mazi", 21, 7000, "jiangxi", "男"));
    personList.add(new Person(5, "laoer", 22, 8000, "zhejiang", "女"));

    String names = personList.stream().map(t -> t.getName()).collect(Collectors.joining(","));
    System.out.println("所有员工的姓名:" + names);
    List<String> list = Arrays.asList("A", "B", "C");
    String string = list.stream().collect(Collectors.joining("&"));
    System.out.println("拼接后的字符串:" + string);

}

//结果
所有员工的姓名:zhangsan,lisi,wanger,mazi,laoer
拼接后的字符串:A&B&C

1.5 归约(reduce)
归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作。

/求和,求积
public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 7, 9);
    
    Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);
    Optional<Integer> sum1 = list.stream().reduce(Integer::sum);
    Integer sum2 = list.stream().reduce(0, Integer::sum);
    
    Optional<Integer> product = list.stream().reduce((x, y) -> x * y);
    // 最大值方式1
    Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);
    // 最大值方式2
    Integer max1 = list.stream().reduce(1, Integer::max);
    System.out.println("求和:" + sum.get() + "," + sum1.get() + "," + sum2);
    System.out.println("求积:" + product.get());
    System.out.println("求和:" + max.get() + "," + max1);
}

//结果
求和:26,26,26
求积:1512
求和:9,9

1.6 聚合(max/min/count)
Collectors提供了一系列用于数据统计的静态方法:

计数:count平均值:averagingInt、averagingLong、averagingDouble最值:maxBy、minBy求和:summingInt、summingLong、summingDouble统计以上所有:summarizingInt、summarizingLong、summarizingDouble

//获取最长元素
public static void main(String[] args) {
    List<String> list = Arrays.asList("asdas", "asdasdasd", "sdasd", "fdfdf", "qqe");
    Optional<String> max = list.stream().max(Comparator.comparing(String::length));
    System.out.println("最长的字符串:" + max.get());
}

//结果
最长的字符串:asdasdasd

1.7 匹配(find/match)

//匹配示例
public static void main(String[] args) {
    List<String> strings = Arrays.asList("123", "456", "abc", "sdf", "qwe", "qw2", "qwe");
    //anyMatch  判断集合中是否至少存在一个元素满足条件
    boolean a = strings.stream().anyMatch("123"::equals);
    System.out.println(a);
    //allMatch 判断集合中是否所有元素都满足条件
    boolean b = strings.stream().allMatch("123"::equals);
    System.out.println(b);
    //noneMatch 判断集合中是否所有元素都不满足条件
    boolean c = strings.stream().noneMatch("123"::equals);
    System.out.println(c);
    //findAny 返回当前流中任意元素
    Optional<String> any = strings.stream().findAny();
    any.ifPresent(System.out::println);
    //findFirst 返回当前流中第一个元素
    Optional<String> first = strings.stream().findFirst();
    first.ifPresent(System.out::println);
}

//结果
true
false
false
123
123
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值