Summary of common usage of Java Stream, greatly improving development efficiency

This article has been included in the Github warehouse, which includes computer foundation, Java foundation, multithreading, JVM, database, Redis, Spring, Mybatis, SpringMVC, SpringBoot, distributed, microservices, design patterns, architecture, school recruitment and social recruitment sharing, etc. Core knowledge points, welcome to star~

Github address

If you can't access Github, you can access the gitee address.

gitee address


The new Stream stream in Java8 has greatly reduced the workload of our code, but there are many usages of Stream stream, and it is easy to forget when actually using it. Let’s sort it out for your reference.

1 Overview

Stream uses an intuitive way similar to using SQL statements to query data from the database to high-level abstraction of Java collection operations and expressions.

The Stream API can greatly improve the productivity of Java programmers, allowing programmers to write efficient, clean, and concise code.

This style regards the collection of elements to be processed as a stream, which is transmitted in the pipeline and can be processed on the nodes of the pipeline, such as filtering, sorting, aggregation, etc.

2. create

2.1 Collection comes with Stream method

List<String> list = new ArrayList<>();
// 创建一个顺序流
Stream<String> stream = list.stream();
// 创建一个并行流
Stream<String> parallelStream = list.parallelStream();

2.1 Create through Array array

The most comprehensive Java interview site

int[] array = {1,2,3,4,5};
IntStream stream = Arrays.stream(array);

2.3 Use the static method of Stream to create

Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
Stream<Integer> stream = Stream.iterate(0, (x) -> x + 3).limit(3); // 输出 0,3,6

Stream<String> stream = Stream.generate(() -> "Hello").limit(3); // 输出 Hello,Hello,Hello
Stream<Double> stream = Stream.generate(Math::random).limit(3); // 输出3个随机数

2.3 Value stream

// 生成有限的常量流
IntStream intStream = IntStream.range(1, 3); // 输出 1,2
IntStream intStream = IntStream.rangeClosed(1, 3); // 输出 1,2,3
// 生成一个等差数列
IntStream.iterate(1, i -> i + 3).limit(5).forEach(System.out::println); // 输出 1,4,7,10,13
// 生成无限常量数据流
IntStream generate = IntStream.generate(() -> 10).limit(3); // 输出 10,10,10

In addition, LongStream and DoubleStream both have these methods.

3. use

Initialize some data, used in the example.

public class Demo {
    class User{
        // 姓名
        private String name;

        // 年龄
        private Integer age;
    }

    public static void main(String[] args) {
        List<User> users = new ArrayList<>();
        users.add(new User("Tom", 1));
        users.add(new User("Jerry", 2));
    }
}

3.1 Traversing forEach

// 循环输出user对象
users.stream().forEach(user -> System.out.println(user));

3.2 Find find

// 取出第一个对象
User user = users.stream().findFirst().orElse(null); // 输出 {"age":1,"name":"Tom"}
// 随机取出任意一个对象
User user = users.stream().findAny().orElse(null);

3.3 match match

// 判断是否存在name是Tom的用户
boolean existTom = users.stream().anyMatch(user -> "Tom".equals(user.getName()));
// 判断所有用户的年龄是否都小于5
boolean checkAge = users.stream().allMatch(user -> user.getAge() < 5);

3.4 filter filter

// 筛选name是Tom的用户
users.stream()
        .filter(user -> "Tom".equals(user.name))
        .forEach(System.out::println); // 输出 {"age":1,"name":"Tom"}

3.5 Mapping map/flatMap

// 打印users里的name
users.stream().map(User::getName).forEach(System.out::println); // 输出 Tom Jerry
// List<List<User>> 转 List<User>
List<List<User>> userList = new ArrayList<>();
List<User> users = userList.stream().flatMap(Collection::stream).collect(Collectors.toList());

3.6 Reduction reduce

// 求用户年龄之和
Integer sum = users.stream().map(User::getAge).reduce(Integer::sum).orElse(0);
// 求用户年龄的乘积
Integer product = users.stream().map(User::getAge).reduce((x, y) -> x * y).orElse(0);

3.7 sort sorted

// 按年龄倒序排
List<User> collect = users.stream()
        .sorted(Comparator.comparing(User::getAge).reversed())
        .collect(Collectors.toList());

//多属性排序
List<Person> result = persons.stream()
                .sorted(Comparator.comparing((Person p) -> p.getNamePinyin())
                        .thenComparing(Person::getAge)).collect(Collectors.toList());

3.8 collect collect

// list转换成map
Map<Integer, User> map = users.stream()
        .collect(Collectors.toMap(User::getAge, Function.identity()));

// 按年龄分组
Map<Integer, List<User>> userMap = users.stream().collect(Collectors.groupingBy(User::getAge));

// 求平均年龄
Double ageAvg = users.stream().collect(Collectors.averagingInt(User::getAge)); // 输出 1.5

// 求年龄之和
Integer ageSum = users.stream().collect(Collectors.summingInt(User::getAge));

// 求年龄最大的用户
User user = users.stream().collect(Collectors.maxBy(Comparator.comparing(User::getAge))).orElse(null);

// 把用户姓名拼接成逗号分隔的字符串输出
String names = users.stream().map(User::getName).collect(Collectors.joining(",")); // 输出 Tom,Jerry

3.9 Duplicate primary key encountered when converting List to Map

This conversion will report an error because the ID is repeated.

can do this

Good things should be shared! I shared the books I have learned about computers for many years, and summarized them into a warehouse of classic computer programming books . There are more than 300 books in total , including C language, C++, Java, Python, front-end, database, operating system, computer network, and data structure. And algorithms, machine learning, programming life, etc., you can star it, next time you find a book directly search on it, the warehouse is continuously updated~

Github address

Guess you like

Origin blog.csdn.net/Tyson0314/article/details/130162505