Jdk8 are 7 years old, you still loop through the list you use for? Stream 3 minutes to learn about it

Brief introduction

Java 8 API adds a new abstraction called stream Stream, allows you to process the data in a declarative way.
Stream uses a similar intuitive way to use SQL statements from the database query data to provide a higher level of abstraction for Java and set operations expression.
This style element to be viewed as a collection of process flow stream in a pipeline transmission, and can be processed on the node conduit, such as filtering, sorting, polymerization.

The students are familiar with Linux certainly no stranger to this style, with Linux because it's |exactly the same idea of the pipe character. This passage quoted from above runoob.com, but the teaching of the code is based on a presentation String list, taking into account the actual situation of 80 percent of the time is right PO, VO processing, the following explain by a PO.

Compared to the for loop operations list, the biggest drawbacks is the code is too long too messy, if the operation involves 3-4 tables, that is, involving multiple PO operation, that is simply parentheses 俄罗斯套娃, and finally wrote really do not know in what to write

flow

+--------------------+       +------+   +------+   +---+   +-------+
| stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
+--------------------+       +------+   +------+   +---+   +-------+

PO Code

public class UserPo {
    private String name;
    private Double score;
    
    // 省略构造函数及getter、setter
}

The following operations are UserPocarried out to explain

filter

filter: filter is a filter, by qualified, does not meet the criteria to filter out

// 筛选出成绩不为空的学生人数
count = list.stream().filter(p -> null != p.getScore()).count();

map

map: map, a collection of original maps become his new collection, more common in the course of VO, PO processing. In the present example, the original set of PO is set, a new set may be mapped to a custom set of results, but also for the new collection related operation

// 取出所有学生的成绩
List<Double> scoreList = list.stream().map(p -> p.getScore()).collect(Collectors.toList());

// 将学生姓名集合串成字符串,用逗号分隔
String nameString = list.stream().map(p -> p.getName()).collect(Collectors.joining(","));

sorted

sorted: sorting, can be sorted according to fields specified

// 按学生成绩逆序排序 正序则不需要加.reversed()
filterList = list.stream().filter(p -> null != p.getScore()).sorted(Comparator.comparing(UserPo::getScore).reversed()).collect(Collectors.toList());

forEach

forEach: This should be the most common, which is customized for each operating element

In addition to data forEach action will change the original set of other operations will not change the original collection, this is sure to attract attention

// 学生成绩太差了,及格率太低,给每个学生加10分,放个水
// forEach
filterList.stream().forEach(p -> p.setScore(p.getScore() + 10));

collect

collect: polymerization, may be used by the specified field GroudBy classification, it may also be used to return a list of strings or patchwork

// 按成绩进行归集
Map<Double, List<UserPo>> groupByScoreMap = list.stream().filter(p -> null != p.getScore()).collect(Collectors.groupingBy(UserPo::getScore));
for (Map.Entry<Double, List<UserPo>> entry : groupByScoreMap.entrySet()) {
    System.out.println("成绩:" + entry.getKey() + " 人数:" + entry.getValue().size());
}

// 返回list
List<Double> scoreList = list.stream().map(p -> p.getScore()).collect(Collectors.toList());
// 返回string用逗号分隔
String nameString = list.stream().map(p -> p.getName()).collect(Collectors.joining(","));

statistics

statistics: statistics can count median, average, maximum and minimum

DoubleSummaryStatistics statistics = filterList.stream().mapToDouble(p -> p.getScore()).summaryStatistics();
System.out.println("列表中最大的数 : " + statistics.getMax());
System.out.println("列表中最小的数 : " + statistics.getMin());
System.out.println("所有数之和 : " + statistics.getSum());
System.out.println("平均数 : " + statistics.getAverage());

parallelStream

parallelStream: parallel streams can multithread operation flow, improve efficiency. However, it does not have a thread propagated, it is necessary to fully assess the need to use a parallel flow operation

// 并行流
count = list.parallelStream().filter(p -> null != p.getScore()).count();

The complete code

package com.cmx.tcn.stream;

/**
 * @author: Cai MinXing
 * @create: 2020-03-25 18:17
 **/
public class UserPo {
    private String name;
    private Double score;

    public UserPo(String name, Double score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

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

    public Double getScore() {
        return score;
    }

    public void setScore(Double score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "UserPo{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }
}

package com.cmx.tcn.stream;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: Cai MinXing
 * @create: 2020-03-25 18:15
 **/
public class StreamTest {

//    +--------------------+       +------+   +------+   +---+   +-------+
//    | stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
//    +--------------------+       +------+   +------+   +---+   +-------+

    public static void main(String args[]){

        List<UserPo> list = new ArrayList<>();
        list.add(new UserPo("小一", 10.d));
        list.add(new UserPo("小五", 50.d));
        list.add(new UserPo("小六", 60.d));
        list.add(new UserPo("小6", 60.d));
        list.add(new UserPo("小空", null));
        list.add(new UserPo("小九", 90.d));

        long count = 0;
        List<UserPo> filterList = null;

        // filter 过滤器的使用
        // 筛选出成绩不为空的学生人数
        count = list.stream().filter(p -> null != p.getScore()).count();
        System.out.println("参加考试的学生人数:" + count);

        // collect
        // 筛选出成绩不为空的学生集合
        filterList = list.stream().filter(p -> null != p.getScore()).collect(Collectors.toList());
        System.out.println("参加考试的学生信息:");
        filterList.stream().forEach(System.out::println);

        // map 将集合映射为另外一个集合
        // 取出所有学生的成绩
        List<Double> scoreList = list.stream().map(p -> p.getScore()).collect(Collectors.toList());
        System.out.println("所有学生的成绩集合:" + scoreList);

        // 将学生姓名集合串成字符串,用逗号分隔
        String nameString = list.stream().map(p -> p.getName()).collect(Collectors.joining(","));
        System.out.println("所有学生的姓名字符串:" + nameString);

        // sorted排序
        // 按学生成绩逆序排序 正序则不需要加.reversed()
        filterList = list.stream().filter(p -> null != p.getScore()).sorted(Comparator.comparing(UserPo::getScore).reversed()).collect(Collectors.toList());
        System.out.println("所有学生的成绩集合,逆序排序:");
        filterList.stream().forEach(System.out::println);

        System.out.println("按学生成绩归集:");
        Map<Double, List<UserPo>> groupByScoreMap = list.stream().filter(p -> null != p.getScore())
                .collect(Collectors.groupingBy(UserPo::getScore));
        for (Map.Entry<Double, List<UserPo>> entry : groupByScoreMap.entrySet()) {
            System.out.println("成绩:" + entry.getKey() + " 人数:" + entry.getValue().size());
        }

        // forEach
        filterList.stream().forEach(p -> p.setScore(p.getScore() + 10));
        System.out.println("及格人数太少,给每个人加10分");
        filterList.stream().forEach(System.out::println);

        // count
        count = filterList.stream().filter(p -> p.getScore() >= 60).count();
        System.out.println("最后及格人数" + count);

        DoubleSummaryStatistics statistics = filterList.stream().mapToDouble(p -> p.getScore()).summaryStatistics();
        System.out.println("列表中最大的数 : " + statistics.getMax());
        System.out.println("列表中最小的数 : " + statistics.getMin());
        System.out.println("所有数之和 : " + statistics.getSum());
        System.out.println("平均数 : " + statistics.getAverage());

        // 并行流 使用
        count = list.parallelStream().filter(p -> null != p.getScore()).count();
        System.out.println("并行流处理参加考试的学生人数:" + count);

    }

}

Published 37 original articles · won praise 21 · views 30000 +

Guess you like

Origin blog.csdn.net/chaitoudaren/article/details/105122681