Java中Stream的使用

Java中Stream的使用

请先了解Lambda表达式的用法,有一定Lambda基础后再进行Stream学习。

Lambda博文链接:Lambda表达式的详解

本文来自于B站博主:倜傥的雷哥 的视频讲解总结

视频链接:
Stream视频详解

1,Stream 处理集合

Stream :流

1.1Stream的概述

Stream 将要处理的元素集合看作一种流,在流的过程中,借助Stream Api 对流中的元素进行操作,比如:筛选,排序,聚合等。

Stream 可以有数组或集合创建,对流的操作分两种:

1.中间操作,每次返回一个新的流,可以有多个。

2.终端操作,每个流只能进行一次终端操作,终端操作结束后流无法再次使用。终端操作会产生一个新的集合或值。

3.Stream不存储数据,而是按照特定的规则对数据进行计算,一般会输出结果。

4.不会改变数据源,通常情况下会产生一个新的集合或值

5.Stream具有延时执行的特性,只有调用终端操作时,中间的操作才会执行。

基础写法 -创建,筛选,聚合
/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/0:15
 * @Description:  Stream流对集合的筛选  
 */
public class Sream01 {
    public static void main(String[] args) {
        List<Item2> list = new ArrayList<>();
        list.add(new Item2(1, "阿萨", 10.22));
        list.add(new Item2(2, "撒旦", 20.21));
        list.add(new Item2(3, "答案", 22.22));
        //以前对集合元素的筛选
        List<Item2> list2 = new ArrayList<>();
        for(Item2 item2:list){
            if(item2.getId()==1||item2.getId()==2){
                list2.add(item2);
                System.out.println(item2);
            }
        }
        //使用Stream流对集合的筛选
        List<Item2> list1=list.stream().filter(t->t.getId()==1||t.getId()==2).collect(Collectors.toList());
        list1.forEach(t->System.out.println(t));
        

    }
}

2,Stream的创建

1.通过Java.util.Collection.stream() 方法用集合创建流

2.使用Java.util.Arrays.stream(T[] array) 方法用数组创建流

3.使用Stream的静态方法: of(), iterate(), generate()

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/0:36
 * @Description:   获取Stream流
 */
public class Stream02 {
    public  static void main(String [] args){
        //1.Collection.stream()方法,用集合创建
        List<String> list = Arrays.asList("1","2","3");
        Stream<String> stream0 =list.stream();

        //2.使用java.util.Arrays.stream(T[] array)方法用数组创建
        String[] arr ={"a","b","c","d"};
        Stream stream1=Arrays.stream(arr);
        Stream stream2=Arrays.stream(arr).sequential();  //顺序流
        Stream stream3=Arrays.stream(arr).distinct();   //去重流


        //3.使用Stream的静态方法: of(),   iterate(),  generate()
        Stream<Integer> integerStream=Stream.of(1,2,3,4,5);
        System.out.println(integerStream);
//        System.out.println(integerStream.max());

        //获取数组中的最大值
        int [] integerArr ={1,2,3,4,5};
        IntStream stream4 = Arrays.stream(integerArr);
        System.out.println(Arrays.stream(integerArr).max().getAsInt());


        Stream limit=Stream.iterate(0,x->x+3).limit(3); //输出0 3  6  迭代功能,第一个参数是起始值.limit限制次数
        limit.forEach(t->System.out.println(t));

        AtomicInteger integer =new AtomicInteger(10); //创建一个原子类 从10开始 每次自增1  自增2次
        Stream<Integer> limit1=Stream.generate(()->integer.incrementAndGet()).limit(2);
        limit1.forEach(System.out::println);

    }
}

3,流的使用

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/1:02
 * @Description:  测试类
 */
public class Person {
    private String name;
    private int salary;
    private int age;
    private String sex;
    private String area;

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

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

    public Person() {
    }

    public String getName() {
        return name;
    }

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

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

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

3.1遍历/匹配
/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/1:06
 * @Description:  测试stream的遍历和匹配
 */
public class Stream03 {
    public static  void main(String [] args){
        List<Integer> list = Arrays.asList(7,6,8,3,2,1,4);
        //顺序遍历 打印出7683214
        list.stream().forEach(System.out::print);
        System.out.println("__________");
        //并行遍历 每次顺序可能不一样
        list.parallelStream().forEach(System.out::print);
        System.out.println("__________");
        //遍历输出符合条件的元素
        //遍历大于6的元素 先找出大于6的元素再组装成新的集合再遍历 打印出7  8
        list.stream().filter(t->t>6).forEach(t->System.out.println(t));
        System.out.println("__________");
        //匹配第一个  打印出7
        System.out.println(list.stream().filter(t->t>6).findFirst().get());
        System.out.println("__________");
        //匹配任意(适用于并行流)  从大于6里面随机取一个
        System.out.println(list.parallelStream().filter(t->t>6).findAny().get());
        System.out.println("__________");
        //是否包含符合特定条件的元素  返回Boolean类型 判断集合是否包含该元素  打印出false
        System.out.println(list.stream().anyMatch(t->t>10));
    }
}

3.2筛选
/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/1:23
 * @Description:  测试Stream筛选
 */
public class Stream04 {
    public static  void main(String [] args){
        List<Integer> list = Arrays.asList(7,6,8,3,2,1,4);
//        筛选大于6的数并遍历
        list.stream().filter(t->t>6).forEach(System.out::println);
        //筛选员工中工资高于8000的人
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("的撒",8000,22,"女","武汉"));
        personList.add(new Person("法按时",7000,22,"女","武汉"));
        personList.add(new Person("的阿萨",7800,22,"男","武汉"));
        personList.add(new Person("答案",12000,12,"女","武汉"));
        personList.add(new Person("滴放",22000,21,"女","北京"));
        //筛选员工中工资高于8000的人
        personList.stream().filter(t->t.getSalary()>8000).forEach(System.out::println);
        System.out.println("_____");
        //筛选员工中工资高于8000的人 ,并形成集合(需要用到归集)
        List<Person> newPersonlist = personList.stream().filter(t->t.getSalary()>8000).collect(Collectors.toList());
        System.out.println(newPersonlist);
    }
}
3.3 聚合(max/min/count)

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/1:35
 * @Description:  聚合(max,min,count)
 */
public class Stream05 {
    public static  void main(String [] args) {
        //1.获取String集合中长度最长的元素  输出大苏打
        List<String> list =Arrays.asList("李磊", "大苏打","da","saa");
        Optional<String> max=list.stream().max(((o1, o2) -> o1.length()-o2.length()));
        System.out.println(max.get());

        //简化 利用比较器
        Optional<String> max2=list.stream().max((Comparator.comparingInt(String::length)));
        System.out.println(max2.get());

        //2.获取Integer集合中的最大值
        //自然排序
        List<Integer> list2 = Arrays.asList(7, 6, 8, 3, 2, 1, 4);
        System.out.println(list2.stream().max(Integer::compareTo).get());
        System.out.println("_________");
        //自定义排序 找到最小的
        System.out.println(list2.stream().max(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        }).get());
        //简化为Comparator.reverseOrder()
        System.out.println(list2.stream().max(Comparator.reverseOrder()).get());
        System.out.println("_________");

        //计数 统计集合中大于4的个数 结果为3
        System.out.println(list2.stream().filter(t->t>4).count());
        List<Integer> list1 = Arrays.asList(7, 6, 8, 3, 2, 1, 4);
//        筛选大于6的数并遍历
        list1.stream().filter(t -> t > 6).forEach(System.out::println);


        //筛选员工中工资高于8000的人
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("的撒", 8000, 22, "女", "武汉"));
        personList.add(new Person("法按时", 7000, 22, "女", "武汉"));
        personList.add(new Person("的阿萨", 7800, 22, "男", "武汉"));
        personList.add(new Person("答案", 12000, 12, "女", "武汉"));
        personList.add(new Person("滴放", 22000, 21, "女", "北京"));

        //获取员工薪资最高的人
        Person person =personList.stream().max(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                return o1.getSalary()-o2.getSalary();
            }
        }).get();
        System.out.println(person);
        Person person2 =personList.stream().max(Comparator.comparingInt(Person::getSalary)).get();
        System.out.println(person2);
    }

}

3.3 映射

映射可以将一个流的元素按照一定的映射规则映射到另一个流中。分为map和flatMap.(注意:这里的map不是集合容器类,别与集合的map混淆!)

1.map:接受一个函数作为参数。该函数会被应用到每个元素上,并将其映射 成一个新的元素。

2.flatmap:接受一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连接成一个流。

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/15:25
 * @Description: 映射可以将一个流的元素按照一定的映射规则**映射到另一个流中。分为map和flatMap.(注意:这里的map不是集合容器类,别与集合的map混淆!)
 *
 * 1.map:接受一个函数作为参数。该函数会被应用到每个元素上,并将其映射 成一个新的元素。
 *
 *2.flatmap:接受一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连接成一个流。
 */
public class Stream06 {
    public static void main(String[] args) {
        //1.将英文字符串数组的元素全部改为大写
        String[] strArr ={"abcd","sad","fds","asaa" };
        List<String> listStr = Arrays.asList(strArr);
        System.out.println(listStr);

        System.out.println("___________");
        //使用map调用转换大写函数映射再直接遍历打印 输出结果为 ABCD	SAD	FDS	ASAA
        listStr.stream().map(t->t.toUpperCase()).forEach(t->System.out.print(t+"\t"));
        System.out.println("___________");
        //也可以规约成一个结合再重新输出如下  输出结果为 [ABCD, SAD, FDS, ASAA]
        List<String> newList = listStr.stream().map(t->t.toUpperCase()).collect(Collectors.toList());
        System.out.println(newList);




        System.out.println("整数数组每个元素加3");
        //整数数组每个元素加3
        Integer[] integers ={1,2,3,3,2,3};
        Arrays.stream(integers).map(t->t+3).forEach(t->System.out.println(t));

        //将员工的工资加1000  输出[9000, 8000, 8800, 13000, 23000](原来的集合中的值也会改变)
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("的撒", 8000, 22, "女", "武汉"));
        personList.add(new Person("法按时", 7000, 22, "女", "武汉"));
        personList.add(new Person("的阿萨", 7800, 22, "男", "武汉"));
        personList.add(new Person("答案", 12000, 12, "女", "武汉"));
        personList.add(new Person("滴放", 22000, 21, "女", "北京"));
        List<Integer> newPersonlist = personList.stream().map(t->{
            t.setSalary(t.getSalary()+1000);
            return t.getSalary();
                }
        ).collect(Collectors.toList());
        System.out.println(newPersonlist);
        //如果需要返回对象(原来的集合中的值也会改变)
//        List<Person> newPersonlist1 = personList.stream().map(t->{
//                    t.setSalary(t.getSalary()+1000);
//                    return t;
//                }
//        ).collect(Collectors.toList());
//        System.out.println(newPersonlist1);
        //不改变原来的值
        List<Person> newPersonlist2 = personList.stream().map( t->{
                 Person person = new Person(t.getName(),t.getSalary(),t.getAge(),t.getSex(),t.getArea());
                 person.setSalary(t.getSalary()+1000);
                 return person;
        }
        ).collect(Collectors.toList());
        System.out.println(newPersonlist2);


        //将两个字符数分割处理后组合并成一个新的字符数组(注意多个流处理合并的时候使用flatMap) 输出结果为[s, a, d, s, a, AADAS]
        List<String> stringList =Arrays.asList("s-a-d-s-a","AADAS");
        List<String> newStrlist = stringList.stream().flatMap(t->{
            //这里会执行两次因为有两个流
            String[] split =t.split("-");
            //将新的数组变成流返回再进行规约
            return Arrays.stream(split);
        }).collect(Collectors.toList());
        System.out.println(newStrlist);




    }


}

3.4规约(reduce)

规约,也称缩减,是把一个流缩减成一个值,能实现对集合求求和,求乘积和求最值操作。(一个集合含多个值通过规约操作最后返回一个值)

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/16:21
 * @Description:  规约,也称缩减,是把一个流缩减成一个值,能实现对集合求求和,求乘积和求最值操作。
 */
public class Stream07 {
    public static void main(String[] args) {
        //1.求Integer集合的元素之和,乘积和最大值
        List<Integer> list = Arrays.asList(1,2,2,4,2,1);
        //以前求和
        int sum =0;
        for (Integer integer:list){
            sum+=integer;
        }
        System.out.println(sum);
        //使用reduce求和    Optional<T> reduce(BinaryOperator<T> accumulator); 第一个得加get()因为返回值类型是 Optional<java.lang.Integer>
        Integer sum1 = list.stream().reduce(Integer::sum).get();
        Integer sum2 = list.stream().reduce(0,Integer::sum);
        Integer sum3 = list.stream().reduce((x,y)->x+y).get();
        System.out.println(sum1);
        System.out.println(sum2);
        System.out.println(sum3);

        System.out.println("--------");
        //求乘积
        Integer cj = list.stream().reduce((x,y)->x*y).get();
        Integer cj2=list.stream().reduce(1,(x,y)->x*y);
        System.out.println(cj2);

        //求最大值1
        Integer max1 = list.stream().max(Integer::compareTo).get();
        System.out.println(max1);
        //求最大值2
        Integer max2 = list.stream().reduce(Integer::max).get();
        System.out.println(max2);
        //求最大值3
        Integer max3 = list.stream().reduce((x,y)->x>y?x:y).get();
        System.out.println(max3);
        //求员工工资之和和最高工资
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("的撒", 8000, 22, "女", "武汉"));
        personList.add(new Person("法按时", 7000, 22, "女", "武汉"));
        personList.add(new Person("的阿萨", 7800, 22, "男", "武汉"));
        personList.add(new Person("答案", 12000, 12, "女", "武汉"));
        personList.add(new Person("滴放", 22000, 21, "女", "北京"));
        //方法一  先找出所有得工资再求和
        Integer sumSalary = personList.stream().map(t->t.getSalary()).reduce(Integer::sum).get();
        System.out.println(sumSalary);

        //方法二
        Integer sumSalary2 = personList.stream().map(t->t.getSalary()).reduce(0,(x,y)->x+y);
        System.out.println(sumSalary2);
        //方法三
        Integer sumSalary3 = personList.stream().map(t->t.getSalary()).reduce((x,y)->x+y).get();
        System.out.println(sumSalary3);

        //求最高工资方法一  s用来存放结果用结果与较高工资比较 返回结果
        Integer maxSalary = personList.stream().reduce(0,(s,p)->s>p.getSalary()?s:p.getSalary(),Integer::sum);
        System.out.println(maxSalary);
        //
    }
}
3.5收集

collect ,收集,可以说是内容最繁多,功能最丰富的部分。从字面上去理解,就是把一个流收集起来,最终可以收集成一个值也可以是一个新的集合。

3.5.1 归集(toList/toSet/toMap)

因为流不存储数据,那么在流的数据完成处理后,需要将流中的数据重新归集到新的集合里。toList,toSet.toMap比较常用,另外还有toCollection,toConcurrentMap等复杂一些的用法。下面一起演示toList,toSet,toMap。

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/18:00
 * @Description: collect ,收集,可以说是内容最繁多,功能最丰富的部分。从字面上去理解,就是把一个流收集起来,最终可以收集成一个值也可以是一个新的集合。
 */
public class Stream08 {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1,3,2,4,5,12,42,12);
        //找出里面的偶数形成新的集合
        List<Integer> newList = list.stream().filter(t->t % 2 ==0).collect(Collectors.toList());
        System.out.println(newList);
        //找出里面的偶数形成一个新的Set集合
        Set newList1 = list.stream().filter(t->t % 2 ==0).collect(Collectors.toSet());
        System.out.println(newList1);

        List<Person> personList = new ArrayList<>();
        personList.add(new Person("的撒", 8000, 22, "女", "武汉"));
        personList.add(new Person("法按时", 7000, 22, "女", "武汉"));
        personList.add(new Person("的阿萨", 7800, 22, "男", "武汉"));
        personList.add(new Person("答案", 12000, 12, "女", "武汉"));
        personList.add(new Person("滴放", 22000, 21, "女", "北京"));
        //找出所有的人名,形成新的集合
        List<String> nameList = personList.stream().map(t->t.getName()).collect(Collectors.toList());
        System.out.println(nameList);

        //将上面的personList转成一个Map<String,Person> 名字作为key
        //以前写法
        Map<String,Person> newMap = new HashMap<>();
        for (Person person:personList){
            newMap.put(person.getName(),person);
        }

        //Stream的写法  用于List转Map
        Map<String,Person> newMap2 = personList.stream().collect(Collectors.toMap(p->p.getName(),p->p));
        System.out.println(newMap2);
    }
}
3.5.2统计

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

计数: count

平均值: averagingInt,averagingLong,averagingDouble

最值: maxBy,minBy

求和:summingInt,summingLong,summingDouble

统计以上所有:summarizingInt,summarizingLong,summarizingDouble

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/18:18
 * @Description: Collection提供了一系列用于数据统计的静态方法:
 */
public class Stream09 {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("的撒", 8000, 22, "女", "武汉"));
        personList.add(new Person("法按时", 7000, 22, "女", "武汉"));
        personList.add(new Person("的阿萨", 7800, 22, "男", "武汉"));
        personList.add(new Person("答案", 12000, 12, "女", "武汉"));
        personList.add(new Person("滴放", 22000, 21, "女", "北京"));

        //统计员工人数输出5
        Long count = personList.stream().count();
        System.out.println(count);
        Long collect =personList.stream().collect(Collectors.counting());
        System.out.println(collect);
        //求平均工资输出11360.0
        Double avgSalary = personList.stream().collect(Collectors.averagingInt(Person::getSalary));
        System.out.println(avgSalary);
        //求最高工资1输出22000
        Integer max1 = personList.stream().map(p->p.getSalary()).reduce(Integer::max).get();
        System.out.println(max1);
        //求最高工资2输出22000
        Integer max2 = personList.stream().map(p->p.getSalary()).collect(Collectors.maxBy(Integer::compareTo)).get();
        System.out.println(max2);
        //求工资之和 输出56800
        Long sum1 = personList.stream().collect(Collectors.summingLong(Person::getSalary));
        System.out.println(sum1);
        //一次性统计所有东西(总数,最大值,最小值,平均值,最大值) 输出IntSummaryStatistics{count=5, sum=56800, min=7000, average=11360.000000, max=22000}
        IntSummaryStatistics collect1 = personList.stream().collect(Collectors.summarizingInt(Person::getSalary));
        System.out.println(collect1);


    }



}
3.5.3分组

分区:将Stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。

分组:将集合分为多个Map,比如员工按性别分组,有单级分组和多级分组。

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/ 18:56
 * @Description: 3.5.3分组
 *
 * 分区:将Stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
 *
 * 分组:将集合分为多个Map,比如员工按性别分组,有单级分组和多级分组
 */
public class Stream10 {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("的撒", 8000, 22, "女", "武汉"));
        personList.add(new Person("法按时", 7000, 22, "女", "武汉"));
        personList.add(new Person("的阿萨", 7800, 22, "男", "武汉"));
        personList.add(new Person("答案", 12000, 12, "女", "武汉"));
        personList.add(new Person("滴放", 22000, 21, "女", "北京"));
        //按员工薪资是否高于8000分组 最后的map只有两个key true 和false
        Map<Boolean,List<Person>> personMap=personList.stream().collect(Collectors.groupingBy(p->p.getSalary()>=8000));
        System.out.println(personMap);


        //按员工性别和地区分组 最后的map只有两个key 男 和女
        Map<String,List<Person>> personMap2=personList.stream().collect(Collectors.groupingBy(p->p.getSex()));
        System.out.println(personMap2);

        //按地区分组 最后的map有多个key key为String类型的地区名
        Map<String,List<Person>> personMap3=personList.stream().collect(Collectors.groupingBy(p->p.getArea()));
        System.out.println(personMap3);
    }
}

3.5.4 接合

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

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/19:06
 * @Description:  joining 可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串
 */
public class Stream11 {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("的撒", 8000, 22, "女", "武汉"));
        personList.add(new Person("法按时", 7000, 22, "女", "武汉"));
        personList.add(new Person("的阿萨", 7800, 22, "男", "武汉"));
        personList.add(new Person("答案", 12000, 12, "女", "武汉"));
        personList.add(new Person("滴放", 22000, 21, "女", "北京"));
        //找出所有的名字,并按, 进行分割,最后返回一个使用,分割好的字符串
        String nameStr= personList.stream().map(t->t.getName()).collect(Collectors.joining(","));
        System.out.println(nameStr);
        //输出a-b-c
        List<String> list = Arrays.asList("a","b","c");
        System.out.println(list.stream().collect(Collectors.joining("-")));
    }
}
3.5.5 排序

sorted,中间操作。有两种排序:

1.sorted(): 自然排序,流中元素需实现Comparable接口

2.sorter(Comparator com) : Comparator 排序器自定义排序

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/19:14
 * @Description: sorted, 中间操作。有两种排序:
 *
 * 1.sorted(): 自然排序,流中元素需实现Comparable接口
 *
 * 2.sorter(Comparator com) : Comparator 排序器自定义排序
 */
public class Stream12 {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("的撒", 8000, 22, "女", "武汉"));
        personList.add(new Person("法按时", 7000, 22, "女", "武汉"));
        personList.add(new Person("的阿萨", 7800, 22, "男", "武汉"));
        personList.add(new Person("答案", 12000, 12, "女", "武汉"));
        personList.add(new Person("滴放", 22000, 21, "女", "北京"));
        //按员工工资升序(自然排序),并取出所有名字
        List<String> names = personList.stream().sorted(Comparator.comparingInt(Person::getSalary)).map(p->p.getName()).collect(Collectors.toList());
        System.out.println(names);
        //按员工工资倒序
        List<String> names2 = personList.stream().sorted(Comparator.comparingInt(Person::getSalary).reversed()).map(p->p.getName()).collect(Collectors.toList());
        System.out.println(names2);
    }
}

3.5.6 提取/组合

流可以进行合并,去重,限制,跳过等操作

/**
 * Create with IntelliT IDEA
 *
 * @Author: zhengmingzhe
 * @Date: 2022/07/31/19:21
 * @Description:  流可以进行合并,去重,限制,跳过等操作
 */
public class Stream13 {
    public static void main(String[] args) {
        String[] arr1 ={"a","b","c","d"};
        String[] arr2 ={"d","e","f","g"};

        //将两个数组合并   [a, b, c, d, d, e, f, g]
        List<String> collect = Stream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).collect(Collectors.toList());
        System.out.println(collect);
        //合并并去重    [a, b, c, d, e, f, g]
        List<String> collect2 = Stream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).distinct().collect(Collectors.toList());
        System.out.println(collect2);
        //合并去重并只显示前三个  [a, b, c]
        List<String> collect3 = Stream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).distinct().limit(3).collect(Collectors.toList());
        System.out.println(collect3);
        //合并去重并只显示前三个 跳过一个元素获取  [b, c, d]
        List<String> collect4 = Stream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).distinct().skip(1).limit(3).collect(Collectors.toList());
        System.out.println(collect4);
    }
}

语:

恭喜你终于看完啦,还是一句话,看完了并不代表你真的学会了,这些语法只能孰能生巧,请多加练习~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

厌世小晨宇yu.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值