Stream API 流使用的详细示例

2023-12-13 10:32:10

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
public class Java8StreamDemo {

    public static List<Person> builderList() {
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, 20, "male", "New York"));
        personList.add(new Person("Jack", 7000, 18, "male", "Washington"));
        personList.add(new Person("Lily", 7800, 18, "female", "Washington"));
        personList.add(new Person("Anni", 8200, 25, "female", "New York"));
        personList.add(new Person("Owen", 9500, 22, "male", "New York"));
        personList.add(new Person("Alisa", 7900, 28, "female", "New York"));
        personList.add(new Person("Alisa", 7900, 28, "female", "New York"));
        return personList;
    }

    public static void main(String[] args) {
        List<Person> personList = builderList();
        streamTest1(personList);
        streamTest2(personList);
        streamTest3(personList);
        streamTest4(personList);
        streamTest5(personList);
//        list();
    }

    /**
     * 遍历/匹配/过滤
     * allMatch:接收一个 Predicate 函数,当流中每个元素都符合该断言时才返回true,否则返回false
     * noneMatch:接收一个 Predicate 函数,当流中每个元素都不符合该断言时才返回true,否则返回false
     * anyMatch:接收一个 Predicate 函数,只要流中有一个元素满足该断言则返回true,否则返回false
     * findFirst:返回流中第一个元素
     * findAny:返回流中的任意元素
     */
    public static void streamTest1(List<Person> personList) {
        // 遍历
        personList.forEach(p -> System.out.println(p.getName()));

        // 过滤
        List<Person> list = personList.stream().filter(item -> item.getAge() > 23).collect(Collectors.toList());
        list.forEach(p -> System.out.println(p.toString()));

        //匹配
        //list中任意一个满足条件返回true
        boolean anyMatch = personList.stream().anyMatch(p -> p.getAge() > 18); //
        System.out.println("anyMatch:" + anyMatch);

        //list中全部满足条件返回true
        boolean allMatch = personList.stream().allMatch(p -> p.getSex().equals("male"));
        System.out.println("allMatch:" + allMatch);

        //list中全部不满足条件返回true
        boolean noneMatch = personList.stream().noneMatch(p -> p.getSex().equals("111"));
        System.out.println("noneMatch:" + noneMatch);
        //
        Optional<Person> person = personList.stream().findFirst();
        Person person1 = personList.stream().findFirst().orElse(new Person("Alisa", 7900, 28, "female", "New York"));
        Optional<Person> person2 = personList.stream().findAny();
        System.out.println("person:" + person);
        System.out.println("person1:" + person1);
        System.out.println("person2:" + person2);

    }


    /**
     * 聚合(max/min/count)
     * count:返回流中元素的总个数
     * max:返回流中元素最大值
     * min:返回流中元素最小值
     * sum:元素总和
     * average:元素平均素
     *
     * @param personList
     */
    public static void streamTest2(List<Person> personList) {

        Optional<Person> person = personList.stream().max(Comparator.comparing(Person::getSalary));
        System.out.println("max:" + person.get());
        Optional<Person> person2 = personList.stream().min(Comparator.comparing(Person::getAge));
        System.out.println("min:" + person2.get());
        long count = personList.stream().map(Person::getSalary).count();
        System.out.println("元素的总个数count:" + count);
        Integer integer1 = personList.stream().mapToInt(Person::getSalary).sum();
        System.out.println("金额总数:" + integer1);
        Integer integer2 = personList.stream().map(Person::getSalary).reduce(0, Integer::sum);
        System.out.println("金额总数:" + integer2);
        double average = personList.stream().mapToInt(Person::getSalary).average().getAsDouble();
        System.out.println("人均金额:" + average);
    }

    /**
     * 筛选与切片
     * filter:过滤流中的某些元素
     * limit(n):获取n个元素
     * skip(n):跳过n元素,配合limit(n)可实现分页
     * distinct:通过流中元素的 hashCode() 和 equals() 去除重复元素*
     */
    public static void streamTest3(List<Person> personList) {

        List<Person> collect = personList.stream().limit(3).collect(Collectors.toList());
        collect.forEach(System.out::println);

        //分页
        List<Person> collect2 = personList.stream().skip(3).limit(2).collect(Collectors.toList());
        collect2.forEach(System.out::println);

        //对象去重
        List<Person> personList1 = personList.stream().distinct().collect(Collectors.toList());
        personList1.forEach(System.out::println);
 
        //地区去重
        List<String> areaList = personList.stream().map(Person::getArea).distinct().collect(Collectors.toList());
        areaList.forEach(System.out::println);
  
        //按照某个属性去重
        List<Person> areaList2 =
                personList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(Person::getArea))), ArrayList::new));
        areaList2.forEach(System.out::println);
   
    }

    /**
     * 分组groupingBy
     * * 排序 sorted
     *
     * @param personList
     */
    public static void streamTest4(List<Person> personList) {

        //以地区分组
        Map<String, List<Person>> stringListMap = personList.stream().collect(Collectors.groupingBy(Person::getArea));
        System.out.println(stringListMap);
        stringListMap.forEach((k, v) -> {
            System.out.print(k + " --- ");
            System.out.println(v);

        });
    
        //以性别分区
        Map<Boolean, List<Person>> male = personList.stream().parallel().collect(Collectors.partitioningBy(person -> person.getSex().equals("male"), Collectors.toList()));
        male.forEach((k, v) -> {
            System.out.print(k + " *** ");
            System.out.println(v);
        });
        // list->map
        //以唯一key分组
        Map<String, Person> personMap = personList.stream().distinct().collect(Collectors.toMap(Person::getName, Function.identity()));
        personMap.forEach((k, v) -> {
            System.out.print(k + " ### ");
            System.out.println(v);
        });
        Map<String, Person> userMap = personList.stream().collect(Collectors.toMap(Person::getName, a -> a, (k1, k2) -> k1));
        userMap.forEach((k, v) -> {
            System.out.print(k + " $$$ ");
            System.out.println(v);
        });
        //按年龄排序,默认正序
        List<Person> collect = personList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());
        collect.forEach(System.out::println);

        //排序 -倒序 reversed
        List<Person> personList11 = personList.stream().sorted(Comparator.comparing(Person::getAge).reversed()).collect(Collectors.toList());
        personList11.forEach(System.out::println);

        List<Person> personList1 = personList.stream().sorted(
                Comparator.comparing(Person::getAge, Comparator.nullsFirst(Integer::compareTo))
                        .thenComparing(Person::getArea, Comparator.nullsFirst(String::compareTo))
                        .thenComparing(Person::getSalary, Comparator.nullsFirst(Integer::compareTo))
        ).collect(Collectors.toList());
        personList1.forEach(System.out::println);

        //重新创建新对象列表
        List<Student> studentList = personList.stream().map(person -> {
            Student student = new Student(person.getName(), person.getAge(), person.getSex(), person.getArea());
            return student;
        }).collect(Collectors.toList());
        studentList.forEach(System.out::println);

        ArrayList<Object> arrayList = personList.stream().collect(ArrayList::new, (list, person) -> {
            Student student = new Student(person.getName(), person.getAge(), person.getSex(), person.getArea());
            list.add(student);
        }, List::addAll);
        arrayList.forEach(System.out::println);

    }

    /**
     * map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
     * flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
     * peek:流的数据进行操作
     */
    public static void streamTest5(List<Person> personList) {

        Set<String> collect = personList.stream().map(Person::getName).collect(Collectors.toSet());
        collect.forEach(System.out::println);
        List<List<Person>> list = new ArrayList<>();
        list.add(personList);
        list.add(personList);
        //主要作用就是将几个小List中内容提取,合并成大List
        List<Person> personList1 = list.stream().flatMap(Collection::parallelStream).collect(Collectors.toList());
        personList1.forEach(System.out::println);
        //流的数据进行操作
        List<Person> personList2 = personList.stream().peek(person -> person.setSalary(66666)).collect(Collectors.toList());
        personList2.forEach(System.out::println);
    }

    private static void list() {
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, 20, "male", "New York"));
        personList.add(new Person("Jack", 7000, 18, "male", "Washington"));
        personList.add(new Person("Lily", 7800, 18, "female", "Washington"));
        personList.add(new Person("Anni", 8200, 25, "female", "New York"));

        List<Person> personList2 = new ArrayList<Person>();
        personList2.add(new Person("Lily", 7800, 18, "female", "Washington"));
        personList2.add(new Person("Anni", 8200, 25, "female", "New York"));
        personList2.add(new Person("Owen", 9500, 22, "male", "New York"));
        personList2.add(new Person("Alisa", 7900, 28, "female", "New York"));

        // 交集
        List<Person> collect = personList.stream().filter(person1 ->
                        personList2.stream().noneMatch(person2 -> person2.equals(person1)))
                .collect(Collectors.toList());
        collect.forEach(System.out::println);

        //差集 personList对personList2差集
        List<Person> collect2 = personList2.stream().filter(person2 ->
                        personList.stream().noneMatch(person1 -> person2.equals(person1)))
                .collect(Collectors.toList());
        collect2.forEach(System.out::println);

        //并集
        List<Person> all = new ArrayList<>();
        all.addAll(personList);
        all.addAll(personList2);
        List<Person> list = all.stream().distinct().collect(Collectors.toList());
        list.forEach(System.out::println);
    }
}

@Data
@ToString
@EqualsAndHashCode
class Person {

    private String name;  // 姓名
    private int salary; // 薪资
    private int age; // 年龄
    private String sex; //性别
    private String 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;
    }
}

@Data
@ToString
@EqualsAndHashCode
class Student {

    private String name;  // 姓名
    private int age; // 年龄
    private String sex; //性别
    private String area;  // 地区

    // 构造方法
    public Student(String name, int age, String sex, String area) {
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.area = area;
    }
}

文章来源:https://blog.csdn.net/qq_35354529/article/details/134895260
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。