java8-Lambda常用用法

32 阅读3分钟

一、创建stream的几种方式

1.集合创建stream

    @Test
    public void test3(){
        List<String> list = new ArrayList<>();
        Stream<String> stream = list.stream();
    }

2.数组创建stream

    @Test
    public void test4() {
        String[] strArr = new String[]{};
        Stream<String> stream = Arrays.stream(strArr);
    }

3.of方法创建

    @Test
    public void test5() {
        Stream<Integer> stream = Stream.of(1, 2, 3);
    }

4.创建无限流

// 0是种子,表示从0开始加2。取前10个偶数
    @Test
    public void test6() {
        Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);
    }
// 生成10个随机数
    @Test
    public void test7() {
        Stream.generate(Math::random).limit(10).forEach(System.out::println);
    }

二、中间操作

filter

过滤

    @Test
    public void test8() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 6, 544, 3, 3, 2, 2);
        list.stream().filter(item -> item != 3).forEach(System.out::println);
    }

limit

截取,获取前3个元素

    @Test
    public void test9() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 6, 544, 3, 3, 2, 2);
        list.stream().limit(3).forEach(System.out::println);
    }

skip

跳过前3个元素

    @Test
    public void test10() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 6, 544, 3, 3, 2, 2);
        list.stream().skip(3).forEach(System.out::println);
    }

Distinct

在使用stream去除重复元素时,可以借助distinct方法。要注意的时在去重对象list时,必须重写对象的hashcode和equals方法。

代码如下:School和Student都重写了hashcode和equals方法,否则无法去重。

 @Test
    public void testDistinct2(){
        List<School> schoolList = new ArrayList<>();

        List studentList = new ArrayList<>();
        Student student = new Student("1", 10);
        studentList.add(student);
        School school = new School("小学", studentList);
        schoolList.add(school);

        List studentList1 = new ArrayList<>();
        Student student1 = new Student("1", 10);
        studentList1.add(student1);
        School school1 = new School("小学", studentList1);

        schoolList.add(school1);

        schoolList.stream().distinct().forEach(System.out::println);
    }

结果如下:

School{name='小学', students=[Student{id='1', age=10}]}

Process finished with exit code 0

map

映射,对每一个元素都进行处理。

    @Test
    public void test11() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 6, 544, 3, 3, 2, 2);
        list.stream().map(item -> item + 2).forEach(System.out::println);
    }

flatMap

将每一个元素都转换成一个流,并将所有的流连在一起。

    @Test
    public void test12() {
        List<String> list = Arrays.asList("aa", "bb", "cc");
        list.stream().flatMap(StreamTest::stringToStream).forEach(System.out::println);
    }

    public static Stream<Character> stringToStream(String str) {
        List<Character> list = new ArrayList<>();
        for (char c : str.toCharArray()) {
            list.add(c);
        }
        return list.stream();
    }

sorted

自然排序

    @Test
    public void test13() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 6, 544, -3, -23, -72, -52);
        list.stream().sorted().forEach(System.out::println);
    }

定制排序

    @Test
    public void test14() {
        Student student1 = new Student("1", 10);
        Student student2 = new Student("2", 20);
        Student student3 = new Student("3", 9);
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.stream().sorted((s1,s2) -> {
            return Integer.compare(s1.getAge(), s2.getAge());
        }).forEach(System.out::println);
    }

终止操作

allMatch

每个元素都满足条件返回true;

    @Test
    public void test15() {
        Student student1 = new Student("1", 10);
        Student student2 = new Student("2", 20);
        Student student3 = new Student("3", 9);
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        boolean allMatch = list.stream().allMatch(item -> item.getAge() > 8);
        System.out.println(allMatch);
    }

anyMatch

只要有一个元素满足条件就返回true;

    @Test
    public void test15() {
        Student student1 = new Student("1", 10);
        Student student2 = new Student("2", 20);
        Student student3 = new Student("3", 9);
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        boolean anyMatch = list.stream().anyMatch(item -> item.getAge() > 15);
        System.out.println(anyMatch);
    }

noneMatch

没有一个元素满足条件返回true;

    @Test
    public void test15() {
        Student student1 = new Student("1", 10);
        Student student2 = new Student("2", 20);
        Student student3 = new Student("3", 9);
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        boolean noneMatch = list.stream().noneMatch(item -> item.getAge() > 21);
        System.out.println(noneMatch);
    }

findFirst

返回第一个元素;

    @Test
    public void test15() {
        Student student1 = new Student("1", 10);
        Student student2 = new Student("2", 20);
        Student student3 = new Student("3", 9);
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        Optional<Student> first = list.stream().findFirst();
        System.out.println(first.get());
    }

findAny

取任意一个元素

    @Test
    public void test15() {
        Student student1 = new Student("1", 10);
        Student student2 = new Student("2", 20);
        Student student3 = new Student("3", 9);
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        Optional<Student> any = list.stream().findAny();
        System.out.println(any.get());
    }

count

返回流中元素的个数;

    @Test
    public void test15() {
        Student student1 = new Student("1", 10);
        Student student2 = new Student("2", 20);
        Student student3 = new Student("3", 9);
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        long count = list.stream().count();
        System.out.println(count);
    }

max/min

取最大,最小值

    @Test
    public void test15() {
        Student student1 = new Student("1", 10);
        Student student2 = new Student("2", 20);
        Student student3 = new Student("3", 9);
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        Optional<Integer> max = list.stream().map(item -> item.getAge()).max(Integer::compare);
        System.out.println(max.get());
    }

forEach

内部迭代

    @Test
    public void test11() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 6, 544, 3, 3, 2, 2);
        list.stream().forEach(System.out::println);
    }

归约

reduce

将流中的元素反复结合起来,返回一个新值。10是一个起始值。

    @Test
    public void test16() {
        List<Integer> list = Arrays.asList(1, 2, 3);
        Integer reduce = list.stream().reduce(10, (a, b) -> {
            return a + b;
        });
        System.out.println(reduce);
    }
    @Test
    public void test17() {
        Student student1 = new Student("1", 10);
        Student student2 = new Student("2", 20);
        Student student3 = new Student("3", 9);
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        Optional<Integer> reduce = list.stream().map(item -> item.getAge()).reduce(Integer::sum);
        System.out.println(reduce.get());
    }

收集

Collector.toList()与Collector.toSet()用法一致。但set在去重对象时,需要对象重写hashcode和equals方法。

 @Test
    public void test18() {
        Student student1 = new Student("1", 10);
        Student student2 = new Student("2", 20);
        Student student3 = new Student("1", 10);
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);

        Set<Student> collect = list.stream().collect(Collectors.toSet());
        collect.forEach(System.out::println);
    }