(六)jdk8学习心得之Stream流

六、Stream流

1、 什么是stream流

现阶段,可以把stream流看成一个高级版的Iterator。普通的Iterator只能实现遍历,遍历做什么,就需要具体些功能代码函数了。而这个stream可以实现一些遍历常见的功能(例如:非空、求最大值、遍历打印等)

2、 效率高吗?

采用lazy模式(懒处理模式),所有操作最后一起执行,在一次循环中结束。

3、 创建stream流

1) list集合

list对象.stream()即可

2) 数组

Arrays.stream(数组对象)

或者

Stream.of(数组对象)

4、 常见的方法

(六)jdk8学习心得之Stream流

例如:

package com.lennar.jdk8learn.learn;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class LeanStream {

@Test
    public void test1() {
        List<String> list
= new ArrayList<>();
        String[] strings = new String[10];
        for (int i = 0; i < 10; i++) {
            list.add(String.valueOf(i));
            strings[i]
= String.valueOf(i);
        }

//创建流stream
        Stream listStream
= list.stream();
        Stream arrayStream
= Arrays.stream(strings);
        Stream arrayStream2
= Stream.of(strings);
        //forEach遍历方法
        listStream.forEach(System.out::println);
        System.out.println("---------------");
        arrayStream.forEach(System.out::println);
        System.out.println("---------------");
        arrayStream2.forEach(System.out::println);
        System.out.println("---------------");
    }

@Test
    public void test2() {
        Student student1 = new Student("1", "张三", "唐山");
        Student student2 = new Student("2", "李四", "唐山");
        Student student3 = new Student("3", "王五", "北京");
        Student student4 = new Student("4", "赵六", "杭州");
        List<Student> list
= new ArrayList<>();
        list.add(student1);
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        //collect方法:将Steam流转换成list、set、map
        List<Student> newList
= list.stream().collect(Collectors.toList());
        System.out.println(newList);
        Set<Student> set = list.stream().collect(Collectors.toSet());//去重
        System.out.println(set);
        //Collectors.toMap(获取key的方法,获取value的方法,key相同时的方法)
        Map<String, Student> map = list.stream().collect(Collectors.toMap(Student::getName, student -> student, (k1, k2) -> k1));//name作key,student对象作value,键相同则取前者。
        System.out.println(map);
        Map<String, Student> map2 = list.stream().collect(Collectors.toMap(Student::getId, student -> student, (k1, k2) -> k1));
        System.out.println(map2);
        Map<String, Student> map3 = list.stream().collect(Collectors.toMap(Student::getAddress, student ->
student, (k1, k2)
-> k2));
        System.out.println(map3);
        //Collectors.groupingBy(获取分组key的方法)
        Map<String, List<Student>>
groupMap = list.stream().collect(Collectors.groupingBy(Student::getId));
        System.out.println(groupMap);
        Map<String, List<Student>>
groupMap2 = list.stream().collect(Collectors.groupingBy(Student::getName));
        System.out.println(groupMap2);
        Map<String, List<Student>>
groupMap3 = list.stream().collect(Collectors.groupingBy(Student::getAddress));
        System.out.println(groupMap3);
        //最大max(里面本质就是一个Comparator的方法)、最小min(里面本质就是一个Comparator的方法)
        //Comparator.comparing(获取要比较的属性的方法)
        Optional<Student> minStudentOptional = list.stream().min(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return -o1.getId().compareTo(o2.getId());
            }
        });
        Student minStudent = minStudentOptional.get();
        System.out.println("min:" + minStudent);
        Optional<Student> maxStudentOptional = list.stream().max(Comparator.comparing(Student::getId));
        Student maxStudent = maxStudentOptional.get();
        System.out.println(maxStudent);
        //排序sorted(里面本质就是一个Comparator的方法)
        List<Student> students
= list.stream().sorted(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return -o1.getId().compareTo(o2.getId());
            }
        }).collect(Collectors.toList());
        System.out.println(students);
        List<Student> students2
= list.stream().sorted(Comparator.comparing(Student::getId)).collect(Collectors.toList());
        System.out.println(students2);
        //过滤filter(里边返回一个boolean类型数据就行)
        List<Student> filterList
= list.stream().filter(student
-> {
            boolean flag = false;
            if (!student.getAddress().equals("唐山")) {
                flag = true;
            } else {
                if (!student.getId().equals("1")) {
                    flag = true;
                }
            }
            return flag;
        }).collect(Collectors.toList());
        System.out.println(filterList);
        //limit(n),仅仅研究前n个
        List<Student> limitList
= list.stream().limit(2).collect(Collectors.toList());
        System.out.println(limitList);
        //skip(n),跳过前n个
        List<Student> skipList
= list.stream().skip(2).collect(Collectors.toList());
        System.out.println(skipList);
        //distict(),去重
        List<Student> distinctList
= list.stream().distinct().collect(Collectors.toList());
        System.out.println(distinctList);
        //map(把原内容变成新内容的方法)
        List<String> nameList
= list.stream().map(student
-> student.getName()).collect(Collectors.toList());
        System.out.println(nameList);
        //allMatch(匹配方法lambda表达式),都匹配返回true;对每一个元素判断,最后取交集
        Boolean f1 = list.stream().allMatch(student
-> {
            boolean flag = false;
            if (null == student.getName()) {
                flag = true;
            }
            return flag;
        });
        System.out.println(f1);
        //anyMatch(匹配方法lambda表达式),有元素匹配返回true;对每一个元素判断,最后取交集
        boolean f2 = list.stream().anyMatch(student
-> {
            boolean flag = false;
            if ("张三".equals(student.getName())) {
                flag = true;
            }
            return flag;
        });
        System.out.println(f2);
        //noneMatch(匹配方法lambda表达式),都不匹配返回true;对每一个元素判断,最后取交集
        boolean f3 = list.stream().noneMatch(student
-> {
            boolean flag = false;
            if ("唐山".equals(student.getAddress())) {
                flag = true;
            }
            return flag;
        });
        System.out.println(f3);
    }

@Test
    public void test3() {
        List<Integer> list
= new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            list.add(i);
        }
        IntSummaryStatistics collect = list.stream().collect(Collectors.summarizingInt(value -> value));
        System.out.println(collect.getSum());
        System.out.println(collect.getMax());
        System.out.println(collect.getMin());
        System.out.println(collect.getAverage());
        System.out.println(collect.getCount());

List<Double> list2
= new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            list2.add((double) i);
        }
        DoubleSummaryStatistics collect2 = list2.stream().collect(Collectors.summarizingDouble(value -> value));
        System.out.println(collect2.getSum());
        System.out.println(collect2.getMax());
        System.out.println(collect2.getMin());
        System.out.println(collect2.getAverage());
        System.out.println(collect2.getCount());
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class Student {
    private String id;
    private String name;
    private String address;
}

上一篇:C# 延迟处理类 Lazy


下一篇:ApacheOFBiz的相关介绍以及使用总结(二)