stream — 筛选与切片(二)

* filter—接收Lambda,从流中排除某些元素。
* 1imit-截断流,使其元素不超过给定数量。
* skip(n)-跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流,与1imit(n)互补。
* distinct-筛选,通过流所生成元素的hashCode()和equals()去除重复元素。

    List<Employee> employees = Arrays.asList(//
            new Employee(20, "张三", 5000.35), //
            new Employee(40, "李四", 6500.63), //
            new Employee(30, "王五", 4000.93), //
            new Employee(50, "赵六", 9005.36), //
            new Employee(10, "马七", 1050.93), //
            new Employee(10, "马七", 1050.93), //
            new Employee(10, "马七", 1050.93), //
            new Employee(10, "马七", 1050.93), //
            new Employee(20, "朱八", 3000.73)//
    );

1、外部迭代

    @Test
    public void test0() {
        Iterator<Employee> iterator = employees.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

2、filter内部迭代:由steam api完成

    public void test1() {
        // 中间操作
        Stream<Employee> filter = employees.stream().filter((e) -> {
            System.out.println("stream api 中间操作");
            return e.getAge() > 35;
        });
        // 终止操作,一次性执行全部内容:惰性求值
        filter.forEach(System.out::println);
    }

3、limit取满足条件的前2个

    @Test
    public void test2() {
        employees.stream().filter((e) -> {
            System.out.println("满足条件后,后续操作不再进行");
            return e.getSalary() > 50;
        }).limit(2).forEach(System.out::println);
    }

4、skip跳过前2个

    @Test
    public void test3() {
        employees.stream().filter((e) -> e.getSalary() > 50).skip(2).forEach(System.out::println);
    }

5、distinct去重,需重写hashCode和equals

    @Test
    public void test4() {
        employees.stream().filter((e) -> e.getSalary() > 50).distinct().forEach(System.out::println);
    }
原文地址:https://www.cnblogs.com/zhanh247/p/11854434.html