java8流—stream

Ordinary is just two words: laziness and laziness;
success is just two words: hardship and diligence;
excellence is just two words: you and me.
Follow me to learn JAVA, spring family bucket and linux operation and maintenance knowledge from 0, and take you from an ignorant teenager to the peak of life, and marry Bai Fumei!
Follow the WeChat public account [ IT is very reliable  ], and share technical experience every day~ 

 

java8流—stream

 

1 Introduction to java8

      Java 8 (also known as jdk 1.8) is a major version of the Java language development. Oracle Corporation released Java 8 on March 18, 2014. It supports functional programming, a new JavaScript engine, a new date API, a new Stream API, etc. Java8 is a revolutionary, stable and fully functional version.

      At present, basically all companies use the jdk8 version as the compiling and running environment of the company's java system. Based on jdk8, it has the following characteristics or advantages:

      (1) jdk8 has perfect functions : jdk8 can almost meet the development of all java projects;

      (2) Free : jdk8 is free, and subsequent versions such as jdk11 are charged, which is very low cost performance for many companies;

      (3) jdk8 has added several new highlights : stream (parallel stream) processing, lamda expression, new date API and Optional.

 

2 java8流:stream

2.1 Prepare test data

      We define a method getUsers() that returns a List collection of User user objects for subsequent Api testing.

      Define the User.java class:

package com.hc.alltest.all.java8.stream;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 用户
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable, Comparable {

  /**
   * 用户名
   */
  private String name;

  /**
   * 年龄
   */
  private Integer age;

  /**
   * 兴趣爱好
   */
  private List<String> hobbies;

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    User user = (User) o;
    return Objects.equals(getName(), user.getName());
  }

  @Override
  public int hashCode() {

    return Objects.hash(getName());
  }

  /**
   * 默认排序:age升序
   */
  @Override
  public int compareTo(Object o) {
    User user = (User) o;
    return this.age - user.getAge();
  }
}

      Method to get the user list: getUsers()

  /**
   * 获取用户列表
   */
  private static List<User> getUsers() {
    List<User> users = new ArrayList<>();
    users.add(User.builder().name("张三").age(10).hobbies(Arrays.asList("篮球", "乒乓球")).build());
    users.add(User.builder().name("李四").age(30).hobbies(Arrays.asList("游泳", "篮球")).build());
    users.add(User.builder().name("王五").age(20).hobbies(Arrays.asList("小说", "音乐")).build());
    users.add(User.builder().name("小六").age(15).hobbies(Arrays.asList("跑步", "篮球")).build());
    users.add(User.builder().name("李四").age(15).hobbies(Collections.emptyList()).build());
    return users;
  }

 

2.2 filter

      Filter out users who are older than 20 in the collection.

  /**
   * 1.filter:筛选出年龄大于20岁的用户
   */
  private static void filterTest() {
    List<User> users = getUsers();
    users = users.stream()
        .filter(user -> user.getAge() > 20)
        .collect(Collectors.toList());
    log.info("筛选出年龄大于20岁的用户:{}", users);
  }

 

2.3 distinct deduplication

      Deduplication (the same name is considered the same user). Need to override the equals() and hashCode() methods of the User.java class.

  /**
   * 2.distinct:去重(name相同认为是同一用户)
   */
  private static void distinctTest() {
    //users集合里面有两个name为“李四”的用户
    List<User> users = getUsers();
    users = users.stream()
        .distinct()
        .collect(Collectors.toList());
    log.info("去重(name相同认为是同一用户):{}", users);
  }

 

2.4 count

      Count the number of collection elements.

  /**
   * 3.count:统计集合元素个数
   */
  private static void countTest() {
    List<User> users = getUsers();
    long count = users.stream()
        .count();
    log.info("集合元素个数:{}", count);
  }

 

2.5 forEach traversal

      Traverse (loop) processing all elements of the collection.

  /**
   * 4.forEach:遍历(循环)处理集合所有元素
   */
  private static void forEachTest() {
    List<User> users = getUsers();
    users.stream()
        .forEach(user -> {
          //业务处理
          log.info("遍历当前元素为:{}", user);
        });
  }

 

2.6 sorted default sorting

      The collection elements are sorted by default (sorted by age in ascending order). The User.java class needs to implement the Comparable interface and implement the interface abstract method int compareTo(Object o).

  /**
   * 5.sorted:集合元素默认排序(按age升序排序)
   */
  private static void defaultSortedTest() {
    List<User> users = getUsers();
    users = users.stream()
        .sorted()
        .collect(Collectors.toList());
    log.info("默认排序后:{}", users);
  }

 

2.7 sorted specified order sort

      The set elements are sorted (sorted in ascending order by age).

  /**
   * 6.sorted:集合元素指定排序(按age升序排序)
   */
  private static void specifySortedTest() {
    List<User> users = getUsers();
    users = users.stream()
        //.sorted((u1, u2) -> u1.getAge() - u2.getAge())
        .sorted(Comparator.comparingInt(User::getAge))
        .collect(Collectors.toList());
    log.info("指定排序后:{}", users);
  }

 

2.8 reversed reverse order

      The set elements are sorted (sorted in ascending order by age), and reversed.

  /**
   * 7.reversed:集合元素指定排序(按age升序排序),并取反序
   */
  private static void reverseTest() {
    List<User> users = getUsers();
    users = users.stream()
//        .sorted((u1, u2) -> u2.getAge() - u1.getAge())
        .sorted(Comparator.comparingInt(User::getAge).reversed())
        .collect(Collectors.toList());
    log.info("指定排序,并取反序:{}", users);
  }

 

2.9 findFirst to get the first element

      Take the first element in the set.

  /**
   * 8.findFirst:取集合中第一个元素
   */
  private static void findFirstTest() {
    List<User> users = getUsers();
    User firstUser = users.stream()
        .findFirst()
        .orElse(null);
    log.info("集合中第一个元素为:{}", firstUser);
  }

 

2.10 findAny gets any element in the set

      Take any element in the set.

  /**
   * 9.findAny:取集合中任意一个元素
   */
  private static void findAnyTest() {
    List<User> users = getUsers();
    User anyUser = users.stream()
        .findAny()
        .orElse(null);
    log.info("集合中任意一个元素为:{}", anyUser);
  }

 

2.11 min minimum

     Take the youngest element in the set...

  /**
   * 10.min:取集合中年龄最小的元素
   */
  private static void minTest() {
    List<User> users = getUsers();
    User anyUser = users.stream()
        //.min((u1, u2) -> u1.getAge() - u2.getAge())
        .min(Comparator.comparingInt(User::getAge))
        .orElse(null);
    log.info("集合中年龄最小的元素为:{}", anyUser);
  }

 

2.12 max

      Take the oldest element in the set.

  /**
   * 11.max:取集合中年龄最大的元素
   */
  private static void maxTest() {
    List<User> users = getUsers();
    User anyUser = users.stream()
        //.max((u1, u2) -> u1.getAge() - u2.getAge())
        .max(Comparator.comparingInt(User::getAge))
        .orElse(null);
    log.info("集合中年龄最大的元素为:{}", anyUser);
  }

 

2.13 anyMatch any element matching

      If any element in the set satisfies the condition, it returns true; otherwise, it returns false.

  /**
   * 12.anyMatch:集合中任意一个元素满足条件,返回true;反之,返回false
   */
  private static void anyMatchTest() {
    List<User> users = getUsers();
    boolean matchFlag = users.stream()
        .anyMatch(user -> Objects.equals(user.getName(), "李四"));
    log.info("集合中是否存在名为'李四'的元素:{}", matchFlag);
  }

 

2.14 allMatch all elements match

      If all elements in the collection meet the condition, return true; otherwise, return false.

  /**
   * 13.allMatch:集合中所有元素满足条件,返回true;反之,返回false
   */
  private static void allMatchTest() {
    List<User> users = getUsers();
    boolean matchFlag = users.stream()
        .allMatch(user -> user.getAge() > 20);
    log.info("集合中所有元素的年龄是否都大于20岁:{}", matchFlag);
  }

 

2.15 noneMatch all elements do not match

      If all elements in the collection do not satisfy the condition, return true; otherwise, return false.

  /**
   * 14.noneMatch:集合中所有元素都不满足条件,返回true;反之,返回false
   */
  private static void noneMatchTest() {
    List<User> users = getUsers();
    boolean matchFlag = users.stream()
        .noneMatch(user -> user.getAge() <= 20);
    log.info("集合中是否所有元素的年龄都不小于等于20岁:{}", matchFlag);
  }

 

2.16 map set value mapping

       Set value mapping.

  /**
   * 15.map:集合值映射
   */
  private static void mapTest() {
    List<User> users = getUsers();
    List<String> names = users.stream()
//        .map(user -> user.getName())
        .map(User::getName)
        .collect(Collectors.toList());
    log.info("集合中所有对象的名称集合为:{}", names);
  }

 

2.17 flatMap set value flat mapping

      Flat mapping of set values.

  /**
   * 16.flatMap:集合值扁平映射
   */
  private static void flatMapTest() {
    List<User> users = getUsers();
    List<String> allHobbies = users.stream()
        .flatMap(user -> user.getHobbies().stream())
        .collect(Collectors.toList());
    log.info("集合中所有用户的所有兴趣爱好列表:{}", allHobbies);
  }

 

2.18 map+reduce aggregation evaluation

      Aggregate evaluation.

  /**
   * 17.map+reduce:聚合求值
   */
  private static void mapReduceTest() {
    List<User> users = getUsers();
    int ageSum = users.stream()
//        .map(user -> user.getAge())
        .map(User::getAge)
        .reduce(0, (age1, age2) -> age1 + age2);
    log.info("集合中所有用户年龄总和:{}", ageSum);
  }

 

2.19 parallel parallel stream

      Parallel stream processing.

  /**
   * 18.parallel:并行流处理
   */
  private static void parallelStreamTest() {
    List<User> users = getUsers();
    //下面两种方式等效
    users.stream()
        .parallel()
        .forEach(user -> {
          //业务处理
          log.info(".stream.parallel并行遍历当前元素为:{}", user);
        });
    users.parallelStream()
        .parallel()
        .forEach(user -> {
          //业务处理
          log.info(".parallelStream并行遍历当前元素为:{}", user);
        });
  }

      Follow the WeChat public account and reply " I want to stream source code " to get the demo source code, java and related video tutorials of this tutorial for free~

 

Guess you like

Origin blog.csdn.net/IT_Most/article/details/109165956