Stream flow: Examples of intersection, difference set, collection of a certain field, and sorting

Some common operations on stream

  • Intersection
  • Difference set
  • Get a certain field of the collection
  • Set sorting

PS: If you don’t like to read concepts, you can go directly to the source code examples.

anyMatch (intersection)

Determine whether any element in the data list meets the set predicate condition. If so, return true, otherwise return false.

  • Interface definition:
    • boolean anyMatch(Predicate predicate);
  • Method description:
    • In the anyMatch interface definition, it receives a Predicate type parameter. In the Lamdba expression, Predicate receives a T type parameter, and then returns a Boolean result after logical verification. Here anyMatch means that if any element meets the conditions of the judgment, a true value will be returned.
  • Usage scenarios:
    • intersection of two sets
noneMatch (difference set)

It is judged that all elements in the data list do not meet the set predicate conditions. If so, it returns true, otherwise it returns false. When the stream is empty, it always returns true.

  • Interface definition:
    • boolean noneMatch(Predicate predicate);
  • Method description:
    • In the noneMatch interface definition, it receives a Predicate type parameter. In the Lamdba expression, Predicate receives a T type parameter, and then returns a Boolean result after logical verification. Here noneMatch means that it is the opposite of allMatch. If all the elements in the judgment condition are not met, a true value will be returned.
  • Applicable scenarios:
    • Difference of two sets

Source code:

Stream
package com.loong.test.stream;

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

/**
 * Stream flow: Examples of intersection, difference set, collection of a certain field, and sorting
 *
 * @Author: loong
 * @Date: 2023-09-22
 */
public class basicEg {
    public static void main(String[] args) {
        // Set A
        ArrayList<User> userListA = new ArrayList<>();
        userListA.add(new User(1L, "Zhang San", 18,1));
        userListA.add(new User(2L, "李思", 19,1));
        userListA.add(new User(3L, "王二", 20,1));

        //Set B
        ArrayList<User> userListB = new ArrayList<>();
        userListB.add(new User(1L, "Zhang San", null,1));
        userListB.add(new User(3L, "王二", 22,1));

        // Get the intersection A∩B, use equal userId and empty age as the basis for judgment (both conditions must be met), and complete the age in set B using set A as an example as a new set
        List<User> aIntersectB = userListB.stream()
                .filter(userB -> userListB.stream()
                        .anyMatch(userA ->
                                Objects.equals(userB.getUserId(), userA.getUserId())
                                         & amp; & amp; Objects.isNull(userB.getAge())
                        )).collect(Collectors.toList());
        System.out.println("aIntersectB = " + aIntersectB);


        // Take the difference set A\B, based on userI's judgment. The elements belong to set A, but the elements that do not belong to set B are taken out as a new set.
        List<User> aDiffB = userListA.stream()
                .filter(userA -> userListB.stream()
                        .noneMatch(userB ->
                                Objects.equals(userA.getUserId(), userB.getUserId()))).collect(Collectors.toList());

        System.out.println("aDiffB = " + aDiffB);

        // Get a certain field of the collection and get the userId in collection A as a new collection
        List<Long> userIdListA = userListA.stream().map(User::getUserId).collect(Collectors.toList());
        System.out.println("userIdListA = " + userIdListA);


        System.out.println("\
----------------------------------Beautiful dividing line, the following is sorted- ---------------------------------------\
");

        /**
         * Ascending order = positive order
         * Descending order = Reverse order
         *Ascending order by default
         * Descending order plus reversed() or Comparator.reverseOrder()
         *------------------------------------------------ ------
         * Summary of suggestions on the use of reversed() and Comparator.reverseOrder()
         * 1. If multiple conditions are in descending order, reversed() should be written at the end
         * 2. The sorting directions of multiple sorting conditions are inconsistent. Fields that need to be reversed should use Comparator.reverseOrder()
         * 3. The positions added by the two methods are different. Pay attention to identification.
         */
        // set C
        ArrayList<User> userListC= new ArrayList<>();
        userListC.add(new User(1L, "Zhang San", 18,1));
        userListC.add(new User(2L, "李思", 22,1));
        userListC.add(new User(3L, "王二", 19,1));
        userListC.add(new User(4L, "Shen Liu", 19,0));

        // Get a new set by sorting set C in ascending order by age. The default is ascending order, so just use Comparator.comparing(User::getAge).
        List<User> cOrderByAgeAsc = userListC.stream()
                .sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
        System.out.println("cOrderByAgeAsc = " + cOrderByAgeAsc);

        // Sort set C in descending order by age to get a new set. Method 1: Descending order requires reversed()
        List<User> cOrderByAgeDesc = userListC.stream()
                .sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
        System.out.println("cOrderByAgeDesc = " + cOrderByAgeDesc);

        // Sort set C in descending order by age to get a new set. Method 2: Descending order requires Comparator.reverseOrder()
        List<User> cOrderByAgeDesc2 = userListC.stream()
                .sorted(Comparator.comparing(User::getAge,Comparator.reverseOrder())).collect(Collectors.toList());
        System.out.println("cOrderByAgeDesc = " + cOrderByAgeDesc2);

        // Sort set C in descending order by age and in ascending order by status
        List<User> cOrderByAgeDescAndStatusAsc = userListC.stream()
                .sorted(Comparator.comparing(User::getAge,Comparator.reverseOrder())
                        .thenComparing(User::getStatus)).collect(Collectors.toList());
        System.out.println("cOrderByAgeDescAndStatusAsc = " + cOrderByAgeDescAndStatusAsc);

        // Sort set C in descending order by age, and also in descending order by status.
        List<User> cOrderByAgeDescAndStatusDAsc = userListC.stream().
                sorted(Comparator.comparing(User::getAge)
                        .thenComparing(User::getStatus).reversed()).collect(Collectors.toList());

        System.out.println("cOrderByAgeDescAndStatusDAsc = " + cOrderByAgeDescAndStatusDAsc);
        System.out.println("Putting a breakpoint here will help you observe the contents of the collection~");

    }
}
User
package com.loong.test.stream;

/**
 * @Author: loong
 * @Date: 2023-09-22
 */
public class User {
    private Long userId;
    private String userName;
    private Integer age;
    private Integer status;


    public User(Long userId, String userName, Integer age, Integer status) {
        this.userId = userId;
        this.userName = userName;
        this.age = age;
        this.status = status;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + ''' +
                ", age=" + age +
                ", status=" + status +
                '}';
    }
}

**

The knowledge points of the article match the official knowledge archives, and you can further learn related knowledge. Java skill treeBehavioral abstraction and Lambdaflow 132871 people are learning the system