Java jdk8新特性Stream API

首先创建一个Person类备用:

package jdk8;

import java.util.ArrayList;

public class Person implements Comparable<Person>{
    private String name;
    private int age;
    private double salary;

    public Person() {
    }

    public static ArrayList<Person> getList(){
        Person p1 = new Person("张三", 3, 30.0);
        Person p3 = new Person("王五", 5, 50.0);
        Person p2 = new Person("李四", 4, 80.0);
        Person p4 = new Person("赵六", 6, 60.0);
        ArrayList<Person> list = new ArrayList<>();
        list.add(p1);
        list.add(p2);
        list.add(p3);
        list.add(p4);
        return list;
    }
    public Person(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public double getSalary() {
        return salary;
    }

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

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

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        Person person = (Person) o;

        if (age != person.age)
            return false;
        if (Double.compare(person.salary, salary) != 0)
            return false;
        return name != null ? name.equals(person.name) : person.name == null;
    }

    @Override
    public int hashCode() {
        int result;
        long temp;
        result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        temp = Double.doubleToLongBits(salary);
        result = 31 * result + (int) (temp ^ (temp >>> 32));
        return result;
    }

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

获取Stream的四种方式

//获取Stream的四种方式
    @Test
    public void getStream(){
        //方式一:通过Collection得到
        ArrayList<Person> list = Person.getList();
        //串行流
        Stream<Person> s1 = list.stream();
        //并行流
        Stream<Person> ps1 = list.parallelStream();

        //方式二:通过Arrays的stream()方法
        IntStream s2 = Arrays.stream(new int[]{1, 2, 3});

        //方式三:通过Stream的of()方法
        Stream<String> s3 = Stream.of("a", "b", "c");

        //方式四:创建无限流
        //迭代
        Stream<Integer> stream1 = Stream.iterate(0, x -> x * 2);
        //生成
        Stream<Double> stream2 = Stream.generate(() -> Math.random());
    }

Stream的中间操作

//中间操作:筛选
    @Test
    public void testFilter(){
        ArrayList<Person> list = Person.getList();
        Stream<Person> stream = list.stream();
        //forEach()是一个迭代终止操作
        stream.filter(e->e.getAge() > 4).forEach(obj -> System.out.print(obj));
    }

    //中间操作:去除重复元素,需要重写hashcode()和equals()方法
    @Test
    public void testDistinct(){
        ArrayList<Person> list = Person.getList();
        list.add(new Person("张三", 3, 30.0));
        System.out.println(list);
        Stream<Person> stream = list.stream();
        stream.distinct().forEach(System.out::println);
    }

    //中间操作:截取前几个数据
    @Test
    public void testLimit(){
        ArrayList<Person> list = Person.getList();
        Stream<Person> stream = list.stream();
        stream.limit(3).forEach(System.out::println);
    }

    //中间操作:跳过几个数据
    @Test
    public void testSkip(){
        ArrayList<Person> list = Person.getList();
        Stream<Person> stream = list.stream();
        stream.skip(2).forEach(System.out::println);
    }

    //中间操作:映射成一个新的流
    @Test
    public void testMap(){
        ArrayList<Person> list = Person.getList();
        Stream<Person> stream = list.stream();
        stream.map(e->e.getAge()).forEach(System.out::println);
    }

    //中间操作:把流中的每个元素都换成另外一个流
    @Test
    public void testFlatMap(){
        ArrayList<Integer[]> list = new ArrayList();
        list.add(new Integer[]{1,2});
        list.add(new Integer[]{3,4});
        list.stream().forEach(obj-> System.out.println(Arrays.toString(obj)));
        list.stream().map(Arrays::stream).forEach(
                s->s.forEach(obj-> System.out.print(obj + " "))
        );
        System.out.println();
        list.stream().flatMap(Arrays::stream).forEach(obj-> System.out.print(obj + " "));
    }

    //中间操作:排序
    @Test
    public void testSorted(){
        ArrayList<Person> list = Person.getList();
        Stream<Person> stream = list.stream();
        //自然排序,需要实现Comparable接口
        stream.sorted().forEach(System.out::println);

        //定制排序
        list.stream().sorted((o1,o2)-> (int) (o1.getSalary()-o2.getSalary())).forEach(System.out::println);
    }

Stream的终止操作

//终止操作:匹配
    @Test
    public void testMatch(){
        ArrayList<Person> list = Person.getList();
        //是否全部匹配
        boolean b1 = list.stream().allMatch(e -> e.getAge() > 2);
        System.out.println("b1 = " + b1);
        //检查是否至少匹配一个,例如:是否存在姓张
        boolean b2 = list.stream().map(e -> e.getName()).anyMatch(str -> str.startsWith("张"));
        System.out.println("b2 = " + b2);
        //检查是否没有匹配的元素,例如:是否存在薪水大于100
        boolean b3 = list.stream().map(e -> e.getSalary()).noneMatch(t -> t > 100);
        System.out.println("b3 = " + b3);
    }

    //终止操作:查找、计数
    @Test
    public void testFind(){
        ArrayList<Person> list = Person.getList();
        //返回第一个元素
        Optional<Person> first = list.stream().findFirst();
        System.out.println("first = " + first);
        //返回任意一个元素
        Optional<Person> any = list.parallelStream().findAny();
        System.out.println("any = " + any);
        //返回最大值,例如:返回最大的年龄
        Optional<Integer> max = list.stream().map(p -> p.getAge()).max(Integer::compare);
        System.out.println("max = " + max);
        //返回最小值,例如:返回薪水最高的员工
        Optional<Person> min = list.stream().min((p1, p2) -> (int) (p1.getSalary() - p2.getSalary()));
        System.out.println("min = " + min);
        //计数,例如:返回年龄大于4的个数
        long count = list.stream().filter(p -> p.getAge() > 4).count();
        System.out.println("count = " + count);
    }

    //终止操作:归约 
    @Test
    public void testReduce(){
        ArrayList<Person> list = Person.getList();
        //计算薪水总和
        Optional<Double> reduce = list.stream().map(Person::getSalary).reduce((Double::sum));
        System.out.println("reduce = " + reduce);
        //加初始值的归约
        List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
        Integer reduce1 = list1.stream().reduce(10, Integer::sum);
        System.out.println("reduce1 = " + reduce1);
    }

    //终止操作:收集
    @Test
    public void testCollect(){
        ArrayList<Person> list = Person.getList();
        List<Person> tolist = list.stream().collect(Collectors.toList());
        tolist.forEach(System.out::println);

        Double collect = list.stream().map(Person::getAge).collect(Collectors.averagingDouble(a -> (double) a));
        System.out.println("collect = " + collect);
    }

你可能感兴趣的:(Java)