4. Java Stream 中方法

Stream 中方法的使用案例:

limit、sorted、filter、count、findFirst、findAny、map、mapToInt、mapToLong、mapToDouble、flatMap、flatMapToInt、flatMapToLong、flatMapToDouble、anyMatch、allMatch、noneMatch、reduce、toArray

实例:

人员实体:

package com.study.stream;

import java.util.List;
import java.util.Objects;

public class Person implements Comparable<Person>{
    private String name;
    private Integer age;
    private Integer height;

    private List<PresonChildren> presonChildrens;

    public Person(String name, Integer age, Integer height,List<PresonChildren> presonChildrens) {
        this.name = name;
        this.age = age;
        this.height = height;
        this.presonChildrens=presonChildrens;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getHeight() {
        return height;
    }

    public void setHeight(Integer height) {
        this.height = height;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return name.equals(person.name) &&
                age.equals(person.age);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return String.format("姓名:%s;年龄:%s;身高:%s;",this.name,this.age,this.height);
    }

    @Override
    public int compareTo(Person o) {
        return this.getAge().compareTo(o.getAge());
    }

    public List<PresonChildren> getPresonChildrens() {
        return presonChildrens;
    }

    public void setPresonChildrens(List<PresonChildren> presonChildrens) {
        this.presonChildrens = presonChildrens;
    }
}

小孩对象实体:

package com.study.stream;

public class PresonChildren {
    private String chdNmae;

    public PresonChildren(String chdNmae) {
        this.chdNmae = chdNmae;
    }

    public String getChdNmae() {
        return chdNmae;
    }

    public void setChdNmae(String chdNmae) {
        this.chdNmae = chdNmae;
    }
}

案例:

public static void main(String[] agr){

    List<Person> personList= Arrays.asList(
            new Person("张一",18,172,Arrays.asList(new PresonChildren("张一孩子"))),
            new Person("张二",23,175,Arrays.asList(new PresonChildren("张二孩子"))),
            new Person("张三",34,182,Arrays.asList(new PresonChildren("张三孩子"))),
            new Person("张四",12,162,Arrays.asList(new PresonChildren("张四孩子"))),
            new Person("张五",67,184,Arrays.asList(new PresonChildren("张五孩子"))),
            new Person("张六",52,155,Arrays.asList(new PresonChildren("张六孩子"))),
            new Person("张七",41,167,Arrays.asList(new PresonChildren("张七孩子"))),
            new Person("张八",88,176,Arrays.asList(new PresonChildren("张八孩子"))),
            new Person("张九",22,178,Arrays.asList(new PresonChildren("张九孩子"))),
            new Person("张十",20,170,Arrays.asList(new PresonChildren("张十孩子"))),
            new Person("张十一",11,184,Arrays.asList(new PresonChildren("张十一孩子")))
            );

    System.out.println("***************--stream limit--***************************");
    // limit stream 从索引0开始取前3个,顺序从索引0开始
    personList.stream().limit(3).forEach(System.out::println);
    System.out.println("***************--parallelStream limit--***************************");
    // limit parallelStream(并行流)从索引0开始取前3个 ,没有严格顺序
    personList.parallelStream().limit(3).forEach(System.out::println);

    System.out.println("***************--skip--***************************");

    //skip 从第一个开始跳过多少个,
    personList.stream().skip(3).forEach(System.out::println);

    System.out.println("***************--sorted Person 实现接口Comparable 年龄排序--***************************");
    personList.stream().sorted().forEach(System.out::println);


    System.out.println("***************--sorted 定义排序规则 身高排序--***************************");
    personList.stream().sorted((person1,person2) ->{
        return person1.getHeight().compareTo(person2.getHeight());
    }).forEach(System.out::println);


    System.out.println("***************--sorted 定义排序规则 身高,年龄排序--***************************");
    personList.stream().sorted(Comparator.comparing(Person::getHeight,Comparator.naturalOrder()).thenComparing(Person::getAge,Comparator.naturalOrder())).forEach(System.out::println);


    System.out.println("***************--filter 过滤条件,年龄大于25岁的人--***************************");
    personList.stream().filter(person -> {return person.getAge()>25;}).forEach(System.out::println);

    System.out.println("***************--count 集合项数--***************************");
    long streamCount= personList.stream().filter(person -> {return person.getAge()>25;}).count();
    System.out.println("符合条件的项数:"+streamCount);

    System.out.println("***************--findFirst 获取集合第一个--***************************");
    String personStr= personList.stream().findFirst().get().toString();
    System.out.println("第一个对象:"+personStr);

    System.out.println("***************--findAny()操作,返回的元素是不确定的,对于同一个列表多次调用findAny()有可能会返回不同的值。使用findAny()是为了更高效的性能。如果是数据较少,串行地情况下,一般会返回第一个结果,如果是并行的情况,那就不能确保是第一个--***************************");
    String personStr1= personList.stream().findAny().get().toString();
    System.out.println("第一个对象:"+personStr1);

    System.out.println("***************--findAny 获取集合第一个,并行模式下不是第一个--***************************");
    String personStr2= personList.parallelStream().findAny().get().toString();
    System.out.println("不确定对象:"+personStr2);

    System.out.println("***************--map 数据处理后并返回,返回名称-***************************");
    personList.stream().map(Person::getName).forEach(System.out::println);
    System.out.println("***************--map 字符串转大写后返回-*************************");
    List<String> stringList=Arrays.asList("a1","b1","c1","d");
    stringList.stream().map(String::toUpperCase).forEach(System.out::println);


    System.out.println("***************--mapToInt 数据转化为数字,返回数据(mapToLong、mapToDouble)-***************************");
    List<String> listInt = Arrays.asList("3", "6", "8","18", "15");
    listInt.stream().mapToInt(Integer::parseInt).filter(num -> num*2>20).sorted().forEach(System.out::println);

    /**
     * stream中的flatmap是stream的一种中间操作,它和stream的map一样,是一种收集类型的stream中间操作,但是与map不同的是,它可以对stream流中单个元素再进行拆分(切片),从另一种角度上说,使用了它,就是使用了双重for循环。
     *
     * 查看Stream源码中flatmap的方法定义:
     * <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
     * 从方法的定义可以看出,其入参是一个函数式接口,该接口的返回类型应该是Stream< ? extends R > 类型的。
     * stream中的flatmap方法,它的作用就和他的名字flat一样,对于调用flatmap的流的每一个元素,执行flatmap入参中的函数式方法,由于该函数式方法必须返回一个stream<T>类型的流,这样对于调用flatmap的操作来说,就收集了另一种类型(<T>)的流,并在后续的操作中将<T>类型进行合并,最终产生一个stream<T>的流,而不是一个stream<stream<T>>类型的流
     */
    System.out.println("***************-- flatMap 合并集合-***************************");
    Stream.of(stringList,listInt).flatMap(List::stream).forEach(System.out::println);

    System.out.println("***************-- flatMap 对象属性进行stream操作 flatMapToInt、flatMapToLong、flatMapToDouble-***************************");
    personList.stream().flatMap(person -> person.getPresonChildrens().stream()).map(PresonChildren::getChdNmae).forEach(System.out::println);

    /**
     * anyMatch表示,判断的条件里,任意一个元素成功,返回true
     *
     * allMatch表示,判断条件里的元素,所有的都是,返回true
     *
     * noneMatch跟allMatch相反,判断条件里的元素,所有的都不是,返回true
     */

    System.out.println("***************-- anyMatch 判断的条件里,任意一个元素成功,返回true-***************************");
    System.out.println(personList.stream().anyMatch(person -> person.getAge()>45));

    System.out.println("***************-- allMatch表示 判断条件里的元素,所有的都是,返回true-***************************");
    System.out.println(personList.stream().allMatch(person -> person.getAge()>45));

    System.out.println("***************-- noneMatch 判断的条件里,任意一个元素成功,返回true-***************************");
    System.out.println(personList.stream().noneMatch(person -> person.getAge()<145));


    System.out.println("***************-- max 判断的条件里,任意一个元素成功,返回true-***************************");
    List<Integer> listInts = Arrays.asList(3, 6, 8,18, 5);
     int maxValue=listInts.stream().max((a,b) -> {return a.compareTo(b);}).get();
     int minValue=listInts.stream().min((a,b) -> {return a.compareTo(b);}).get();

     int sumValue= listInts.stream().mapToInt(Integer::intValue).sum();
     double avgValue= listInts.stream().mapToInt(Integer::intValue).average().getAsDouble();

     System.out.println(String.format("合计:%d;最大值:%d;最小值:%d;平均值:%f;",sumValue,maxValue,minValue,avgValue));


    System.out.println("***************-- reduce方法用于对stream中元素进行聚合求值-***************************");

    int sumRedValue= listInts.stream().reduce((a,b) -> a+b).get();
    System.out.println("求和:"+sumRedValue);

    System.out.println("***************-- reduce 初始值/追加值 方法用于对stream中元素进行聚合求值-***************************");

    /**
     * 1   Optional<T> reduce(BinaryOperator<T> accumulator);
     * 对Stream中的数据通过累加器accumulator迭代计算,最终得到一个Optional对象
     * 2   T reduce(T identity, BinaryOperator<T> accumulator);
     * 给定一个初始值identity,通过累加器accumulator迭代计算,得到一个同Stream中数据同类型的结果
     * 3   <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);
     * 给定一个初始值identity,通过累加器accumulator迭代计算,得到一个identity类型的结果,第三个参数用于使用并行流时合并结
     * ————————————————
     * 版权声明:本文为CSDN博主「卓立~」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
     * 原文链接:https://blog.csdn.net/weixin_41835612/article/details/83687078
     */

    int sumRedValue1= listInts.stream().reduce(10,(a,b) -> a+b).intValue();
    System.out.println("求和:"+sumRedValue1);


    System.out.println("***************-- reduce 初始值/追加值,改变数据类型 方法用于对stream中元素进行聚合求值-***************************");
    Long sumLongValue = listInts.stream().reduce(10L, (a,b) -> {
        return a+b;
    }, (a, b) -> null);

    System.out.println("求和:"+sumLongValue);

    System.out.println("***************-- toArray 指定类型,集合转数组-***************************");
    Integer[] intToStringList= listInts.stream().toArray(Integer[]::new);

    for (Integer s : intToStringList) {
        System.out.println(s);
    }

    System.out.println("***************-- toArray 不指定类型,集合转数组-***************************");
    Object[] intToStringList1= listInts.stream().toArray();

    for (Object s : intToStringList1) {
        System.out.println(s);
    }






}

执行结果:

***************--stream limit--***************************
姓名:张一;年龄:18;身高:172;
姓名:张二;年龄:23;身高:175;
姓名:张三;年龄:34;身高:182;
***************--parallelStream limit--***************************
姓名:张三;年龄:34;身高:182;
姓名:张一;年龄:18;身高:172;
姓名:张二;年龄:23;身高:175;
***************--skip--***************************
姓名:张四;年龄:12;身高:162;
姓名:张五;年龄:67;身高:184;
姓名:张六;年龄:52;身高:155;
姓名:张七;年龄:41;身高:167;
姓名:张八;年龄:88;身高:176;
姓名:张九;年龄:22;身高:178;
姓名:张十;年龄:20;身高:170;
姓名:张十一;年龄:11;身高:184;
***************--sorted Person 实现接口Comparable 年龄排序--***************************
姓名:张十一;年龄:11;身高:184;
姓名:张四;年龄:12;身高:162;
姓名:张一;年龄:18;身高:172;
姓名:张十;年龄:20;身高:170;
姓名:张九;年龄:22;身高:178;
姓名:张二;年龄:23;身高:175;
姓名:张三;年龄:34;身高:182;
姓名:张七;年龄:41;身高:167;
姓名:张六;年龄:52;身高:155;
姓名:张五;年龄:67;身高:184;
姓名:张八;年龄:88;身高:176;
***************--sorted 定义排序规则 身高排序--***************************
姓名:张六;年龄:52;身高:155;
姓名:张四;年龄:12;身高:162;
姓名:张七;年龄:41;身高:167;
姓名:张十;年龄:20;身高:170;
姓名:张一;年龄:18;身高:172;
姓名:张二;年龄:23;身高:175;
姓名:张八;年龄:88;身高:176;
姓名:张九;年龄:22;身高:178;
姓名:张三;年龄:34;身高:182;
姓名:张五;年龄:67;身高:184;
姓名:张十一;年龄:11;身高:184;
***************--sorted 定义排序规则 身高,年龄排序--***************************
姓名:张六;年龄:52;身高:155;
姓名:张四;年龄:12;身高:162;
姓名:张七;年龄:41;身高:167;
姓名:张十;年龄:20;身高:170;
姓名:张一;年龄:18;身高:172;
姓名:张二;年龄:23;身高:175;
姓名:张八;年龄:88;身高:176;
姓名:张九;年龄:22;身高:178;
姓名:张三;年龄:34;身高:182;
姓名:张十一;年龄:11;身高:184;
姓名:张五;年龄:67;身高:184;
***************--filter 过滤条件,年龄大于25岁的人--***************************
姓名:张三;年龄:34;身高:182;
姓名:张五;年龄:67;身高:184;
姓名:张六;年龄:52;身高:155;
姓名:张七;年龄:41;身高:167;
姓名:张八;年龄:88;身高:176;
***************--count 集合项数--***************************
符合条件的项数:5
***************--findFirst 获取集合第一个--***************************
第一个对象:姓名:张一;年龄:18;身高:172;
***************--findAny()操作,返回的元素是不确定的,对于同一个列表多次调用findAny()有可能会返回不同的值。使用findAny()是为了更高效的性能。如果是数据较少,串行地情况下,一般会返回第一个结果,如果是并行的情况,那就不能确保是第一个--***************************
第一个对象:姓名:张一;年龄:18;身高:172;
***************--findAny 获取集合第一个,并行模式下不是第一个--***************************
不确定对象:姓名:张七;年龄:41;身高:167;
***************--map 数据处理后并返回,返回名称-***************************
张一
张二
张三
张四
张五
张六
张七
张八
张九
张十
张十一
***************--map 字符串转大写后返回-*************************
A1
B1
C1
D
***************--mapToInt 数据转化为数字,返回数据(mapToLong、mapToDouble)-***************************
15
18
***************-- flatMap 合并集合-***************************
a1
b1
c1
d
3
6
8
18
15
***************-- flatMap 对象属性进行stream操作 flatMapToInt、flatMapToLong、flatMapToDouble-***************************
张一孩子
张二孩子
张三孩子
张四孩子
张五孩子
张六孩子
张七孩子
张八孩子
张九孩子
张十孩子
张十一孩子
***************-- anyMatch 判断的条件里,任意一个元素成功,返回true-***************************
true
***************-- allMatch表示 判断条件里的元素,所有的都是,返回true-***************************
false
***************-- noneMatch 判断的条件里,任意一个元素成功,返回true-***************************
false
***************-- max 判断的条件里,任意一个元素成功,返回true-***************************
合计:40;最大值:18;最小值:3;平均值:8.000000;
***************-- reduce方法用于对stream中元素进行聚合求值-***************************
求和:40
***************-- reduce 初始值/追加值 方法用于对stream中元素进行聚合求值-***************************
求和:50
***************-- reduce 初始值/追加值,改变数据类型 方法用于对stream中元素进行聚合求值-***************************
求和:50
***************-- toArray 指定类型,集合转数组-***************************
3
6
8
18
5
***************-- toArray 不指定类型,集合转数组-***************************
3
6
8
18
5

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值