Java 8 Stream API使用

Java8中有两大最为重要的改变。第一个是Lambda表达式,另外一个则是Stream API (java.util.stream.*) 。Stream是Java8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API对集合数据进行操作,就类似于使用SQL执行的数据库查询。也可以使用Stream API来并行执行操作。简而言之,Stream API提供了一种高效、干净、简洁且易于使用的处理数据的方式。

什么是 Stream?

Stream(流)是一个来自数据源的元素队列并支持聚合操作

  • 元素是特定类型的对象,形成一个队列。 Java中的Stream并不会存储元素,而是按需计算。
  • 数据源 流的来源。 可以是集合,数组,I/O channel, 产生器generator 等。
  • 聚合操作 类似SQL语句一样的操作, 比如filter, map, reduce, find, match, sorted等。

和以前的Collection操作不同, Stream操作还有两个基础的特征:

  • Pipelining: 中间操作都会返回流对象本身。 这样多个操作可以串联成一个管道, 如同流式风格(fluent style)。 这样做可以对操作进行优化, 比如延迟执行(laziness)和短路( short-circuiting)。
  • 内部迭代: 以前对集合遍历都是通过Iterator或者For-Each的方式, 显式的在集合外部进行迭代, 这叫做外部迭代。 Stream提供了内部迭代的方式, 通过访问者模式(Visitor)实现。

注意:

  1. Stream自己不会存储元素。
  2. Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream。
  3. Stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

Stream操作的三个步骤

  1. 创建Stream:一个数据源(如:集合、数组),获取一个流。
  2. 中间操作:一个中间操作链,对数据源的数据进行处理。
  3. 终止操作(终端操作):一个终止操作,执行中间操作链,并产生结果。

创建Stream流的四种方式

方法一:通过Collection系列集合提供的两个获取流的方法。

default Stream<E> stream()  :返回一个顺序流。
default Stream<E> parallelStream()  :返回一个并行流。

        List<String> list = new ArrayList<>();
        Stream<String> stream1 = list.stream();

方法二:通过Arrays中的静态方法stream()获取数组流。

        Employee[] employees = new Employee[10];
        Stream<Employee> stream2 = Arrays.stream(employees);

方法三:通过Stream类中的静杰方法of()获取流。

        Stream<String> stream3 = Stream.of("a", "b", "c");

方法四:创建无限流

1).迭代

        //1).迭代
        Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
        stream4.limit(10)//中间操作
                .forEach(System.out::println);//终止操作

2).生成

        //2).生成
        Stream.generate(() -> (int) (Math.random() * 10))
                .limit(10)//中间操作
                .forEach(System.out::println);//终止操作

Stream流的中间操作

多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全部处理,称为“惰性求值”。

例:

/**
 * 筛选与切片
 */
public class TestStreamAPI1 {

    List<Employee> employees = Arrays.asList(
            new Employee("王力宏", 25, 9999.99),
            new Employee("李庆华", 40, 8888.66),
            new Employee("赵金龙", 26, 5555.33),
            new Employee("奈米给", 36, 2222.98),
            new Employee("黄晋琨", 30, 7888.11),
            new Employee("黄晋琨", 30, 7888.11),
            new Employee("黄晋琨", 30, 7888.11)
    );

    /**
     * filter(Predicate<? super T> predicate):接收Lambda,从流中排除某些元素。
     * 内部送代:迭代操作由Stream API完成
     */
    @Test
    public void test01() {
        Stream<Employee> employeeStream = employees.stream()
                .filter((emp) -> {
                    System.out.println("验证Stream API中间操作有没有输出!");
                    return emp.getAge() > 35;
                });
        //终止操作:一次性执行全部内容,即称为“惰性求值”
        employeeStream.forEach(System.out::println);
    }

    /**
     * 外部迭代
     */
    @Test
    public void test02() {
        Iterator<Employee> iterator = employees.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    /**
     * limit(long maxSize):截断流,使其元素不超过给定数量。
     */
    @Test
    public void test03() {
        employees.stream()
                .filter((emp) -> emp.getSalary() > 5000)
                .limit(2)
                .forEach(System.out::println);
    }

    /**
     * skip(long n):跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(long maxSize)互补。
     */
    @Test
    public void test04() {
        employees.stream()
                .filter((emp) -> emp.getSalary() > 5000)
                .skip(2)
                .forEach(System.out::println);
    }

    /**
     * distinct():筛选,通过流所生成元素的hashCode()和equals()去除重复元素。
     */
    @Test
    public void test05() {
        employees.stream()
                .filter((emp) -> emp.getSalary() > 5000)
                .distinct()
                .forEach(System.out::println);
    }
    
}

例:

/**
 * 映射
 */
public class TestStreamAPI2 {

    List<Employee> employees = Arrays.asList(
            new Employee("王力宏", 25, 9999.99),
            new Employee("李庆华", 40, 8888.66),
            new Employee("赵金龙", 26, 5555.33),
            new Employee("奈米给", 36, 2222.98),
            new Employee("黄晋琨", 30, 7888.11)
    );

    /**
     * map:接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
     */
    @Test
    public void test01() {
        List<String> strings = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
        strings.stream()
                .map((str) -> str.toUpperCase())
                .forEach(System.out::println);

        employees.stream()
                .map(Employee::getName)
                .forEach(System.out::println);
    }

    /**
     * flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
     */
    @Test
    public void test02() {
        List<String> strings = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
        //最初始的方法
        Stream<Stream<Character>> stream = strings.stream()
                .map(TestStreamAPI3::filterCharacter);//{{a,a,a},{b,b,b}...}
        stream.forEach((sm) -> {
            sm.forEach(System.out::println);
        });
        System.out.println("************************");
        //利用flatMap方法
        strings.stream()
                .flatMap(TestStreamAPI3::filterCharacter)//{a,a,a,b,b,b...}
                .forEach(System.out::println);
    }

    /**
     * 获取一个字符串,将字符提取出来转换成流。
     *
     * @param string
     * @return
     */
    public static Stream<Character> filterCharacter(String string) {
        List<Character> list = new ArrayList<>();
        for (Character c : string.toCharArray()) {
            list.add(c);
        }
        return list.stream();
    }

}

例:

/**
 * 排序
 */
public class TestStreamAPI3 {

    List<Employee> employees = Arrays.asList(
            new Employee("王力宏", 25, 9999.99),
            new Employee("李庆华", 40, 8888.66),
            new Employee("纳米颗", 40, 8956.66),
            new Employee("赵金龙", 26, 5555.33),
            new Employee("奈米给", 36, 2222.98),
            new Employee("黄晋琨", 30, 7888.11)
    );

    /**
     * sorted():自然排序Comparable
     */
    @Test
    public void test1() {
        List<String> strings = Arrays.asList("ccc", "aaa", "eee", "bbb", "ddd");
        strings.stream()
                .sorted()
                .forEach(System.out::println);
    }

    /**
     * sorted(Comparator<? super T> comparator):定制排序Comparator
     */
    @Test
    public void test2() {
        employees.stream().sorted((e1, e2) -> {
            //如果年龄相同,按姓名排序
            if (e1.getAge().equals(e2.getAge())) {
                return e1.getName().compareTo(e2.getName());
            } else {
                return e1.getAge().compareTo(e2.getAge());
                //倒序排序为
                //return -e1.getAge().compareTo(e2.getAge());
            }
        }).forEach(System.out::println);
    }
}

Stream流的终止操作

终止操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer甚至是void 。

例:

/**
 * 终止操作
 */
public class TestStreamAPI4 {
    List<Employee> employees = Arrays.asList(
            new Employee("王力宏", 25, 9999.99, Employee.Status.HANDSOME),
            new Employee("李庆华", 40, 8888.66, Employee.Status.HANDSOME),
            new Employee("纳米颗", 40, 8956.66, Employee.Status.BEAUTIFUL),
            new Employee("赵金龙", 26, 5555.33, Employee.Status.FREE),
            new Employee("奈米给", 36, 2222.98, Employee.Status.BEAUTIFUL),
            new Employee("黄晋琨", 30, 7888.11, Employee.Status.CUTE),
            new Employee("黄晋琨", 30, 7888.11, Employee.Status.CUTE)
    );

    /**
     * 查找
     */
    @Test
    public void test1() {
        //allMatch:检查是否匹配所有元素
        boolean b1 = employees.stream()
                .allMatch((s) -> s.getStatus().equals(Employee.Status.BEAUTIFUL));
        System.out.println(b1);

        //anyMatch:检查是否至少匹配一个元素
        boolean b2 = employees.stream()
                .anyMatch((s) -> s.getStatus().equals(Employee.Status.BEAUTIFUL));
        System.out.println(b2);

        //noneMatch:检查是否没有匹配所有元素
        boolean b3 = employees.stream()
                .noneMatch((s) -> s.getStatus().equals(Employee.Status.BEAUTIFUL));
        System.out.println(b3);

        //findFirst:返回第一个元素
        Optional<Employee> first = employees.stream()
                .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))//排序工资最低
                .findFirst();
        System.out.println(first.get());

        //findAny:返回当前流中的任意元素
        Optional<Employee> any = employees.stream()
                .filter((emp) -> emp.getStatus().equals(Employee.Status.FREE))//如果是空闲状态找出
                .findAny();
        System.out.println(any.get());
    }

    /**
     * 匹配
     */
    @Test
    public void test2() {
        //count:返回流中元素的总个数
        long count = employees.stream().count();
        System.out.println(count);

        //max:返回流中最大值
        //例:获取工资中的工资最大的员工
        Optional<Employee> max = employees.stream()
                .max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(max.get());

        //min:返回流中最小值
        //例:获取工资中的最小工资
        Optional<Double> min = employees.stream()
                .map(Employee::getSalary)
                .min(Double::compareTo);
        System.out.println(min.get());
    }

    /**
     * 归约
     * reduce(BinaryOperator < T > accumulator)
     * 或
     * reduce(T identity, BinaryOperator < T > accumulator):可以将流中元素反复结合起来, 得到一个值。
     */
    @Test
    public void test3() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        Integer sum = list.stream()
                .reduce(0, (x, y) -> x + y);
        System.out.println(sum);

        //例:员工工资总和
        Optional<Double> opSalarySum = employees.stream()
                .map(Employee::getSalary)
                .reduce(Double::sum);
        System.out.println(opSalarySum.get());
    }

    /**
     * 收集
     * collect:将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法。
     */
    @Test
    public void test4() {
        // 例:将当前员工中所有名字提取出来放入新的集合中
        List<String> collect1 = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toList());
        collect1.forEach(System.out::println);
        System.out.println("********************");
        //Set去重
        Set<String> collect2 = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toSet());
        collect2.forEach(System.out::println);
        System.out.println("********************");
        //特殊收集
        HashSet<String> collect3 = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toCollection(HashSet::new));
        collect3.forEach(System.out::println);
        System.out.println("********************");
        //收集总数
        long count = employees.stream()
                .count();
        System.out.println(count);
        Long collect4 = employees.stream()
                .collect(Collectors.counting());
        System.out.println(collect4);
        System.out.println("********************");
        //工资平均值
        Double collect5 = employees.stream()
                .collect(Collectors.averagingDouble(Employee::getSalary));
        System.out.println(collect5);
        System.out.println("********************");
        //工资总和
        double sum = employees.stream().mapToDouble(Employee::getSalary).sum();
        System.out.println(sum);
        Double collect6 = employees.stream()
                .collect(Collectors.summingDouble(Employee::getSalary));
        System.out.println(collect6);
        System.out.println("********************");
        //最大值 对应员工
        Optional<Employee> collect7 = employees.stream()
                .collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
        System.out.println(collect7.get());
        System.out.println("********************");
        //最小值 工资
        Optional<Double> collect8 = employees.stream()
                .map(Employee::getSalary)
                .collect(Collectors.minBy((Double::compareTo)));
        System.out.println(collect8.get());
        System.out.println("********************");
        //分组
        Map<Employee.Status, List<Employee>> collect9 = employees.stream()
                .collect(Collectors.groupingBy(Employee::getStatus));
        //遍历方式一:
        Iterator<Employee.Status> iterator = collect9.keySet().iterator();
        while (iterator.hasNext()) {
            Employee.Status next = iterator.next();
            List<Employee> employees = collect9.get(next);
            System.out.println(next + "=" + employees);
        }
        //遍历方式二:
        /*collect9.forEach((k, v) -> {
            System.out.println(k + "=" + v);
        });*/
        System.out.println("********************");
        //多级分组
        Map<Employee.Status, Map<String, List<Employee>>> collect10 = employees.stream()
                .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((emp) -> {
                    if (emp.getAge() <= 35) {
                        return "青年";
                    } else if (emp.getAge() < 50) {
                        return "中年";
                    } else {
                        return "老年";
                    }
                })));
        collect10.forEach((k, v) -> {
            System.out.println(k + "=" + v);
        });
        System.out.println("********************");
        //分区:满足条件一个区,不满足条件一个区
        Map<Boolean, List<Employee>> collect11 = employees.stream()
                .collect(Collectors.partitioningBy((emp) -> emp.getSalary() > 5000));
        collect11.forEach((k, v) -> {
            System.out.println(k + "=" + v);
        });
        System.out.println("********************");
        //根据工资汇总:包括总数、总和、最大值、最小值、平均值
        DoubleSummaryStatistics collect12 = employees.stream()
                .collect(Collectors.summarizingDouble(Employee::getSalary));
        System.out.println(collect12.getCount());
        System.out.println(collect12.getSum());
        System.out.println(collect12.getMax());
        System.out.println(collect12.getMin());
        System.out.println(collect12.getAverage());
        System.out.println("********************");
        //姓名连接
        String collect13 = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.joining(","));
        System.out.println(collect13);
    }
}

 

转载请注明出处:BestEternity亲笔。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值