[JDK 8 - Collection and Statistics] 7.1 collector collector

1. collect() method

2. Two overloading methods

2.1 Method 1

2.2 Method 2 (commonly used)

3. The role of Collector

4. The role of Collectors

> Collectors.toList() 

> Collectors.toMap()

> Collectors.toSet()

> Collectors.toCollection(): Collect using a custom data structure that implements Collection

5. Actual combat

Stage 1: Preparation work, the entity class implements the Comparable interface

Stage 2: Example

Results of the


1. collect() method

  • [ Terminal operation ] used to aggregate data in the stream

  • The parameter accepted by the collect method is a Collector

2. Two overloading methods

  • In the Stream interface

2.1 Method 1

    <R> R collect(Supplier<R> supplier,
                  BiConsumer<R, ? super T> accumulator,
                  BiConsumer<R, R> combiner);

2.2 Method 2 (commonly used)

 <R, A> R collect(Collector<? super T, A, R> collector);

3. The role of Collector

  • It is a collector and an interface. Its tool class Collectors provides many factory methods.

4. The role of Collectors

  • Utility class , providing many common collector implementations

> Collectors.toList() 

  • ArrayList::new , creates an ArrayList as an accumulator

  • List::add, the operation on the elements in the stream is to add them directly to the accumulator.

  • The reduce operation addsAll to the subtask aggregation results, and all the results of the latter subtask are directly added to the results of the previous subtask.

  • CH_ID is an unmodifiableSet collection

Collectors.toMap()

Collectors.toSet()

Collectors.toCollection(): Collect using a custom data structure that implements Collection

  • Collectors.toCollection (LinkedList::new)

  • Collectors.toCollection (CopyOnWriteArrayList::new)

  • Collectors.toCollection (TreeSet::new)

5. Actual combat

Stage 1: Preparation work, the entity class implements the Comparable interface

  • The characteristics of TreeSet are that it is sortable and non-repeating, that is, the objects stored in TreeSet must be sortable. If the objects cannot be sorted, this exception will be thrown (cannot be cast to java.lang.Comparable).

package com.learning.javalearning.lambda.chapter5;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class User implements Comparable<User> {
    private int id;
    private String name;
    private String pwd;
    private int age;

    @Override
    public int compareTo(User o) {
        int cmp = age - o.age;
        return cmp != 0 ? cmp : name.compareTo(o.name);
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                ", age=" + age +
                '}';
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public User(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}

Stage 2: Example

import com.learning.javalearning.lambda.chapter5.User;

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

public class CollectDemo {
    public static void main(String[] args) {
        List<User> list = Arrays.asList(new User(1, "陆小凤", 19),
                new User(2, "西门吹雪", 20),
                new User(3, "西门吹雪", 20),//思考为什么返回TreeSet这个User会删除
                new User(4, "叶孤城", 20));
        List<User> result = list.stream().collect(Collectors.toList());
        System.out.println("【不常用】Collectors.toCollection()返回自定义类型:如 Linkedlist");

        List<User> linkedList = list.stream().collect(Collectors.toCollection(LinkedList::new));
        List<User> copyOnWriteArrayList = list.stream().collect(Collectors.toCollection(CopyOnWriteArrayList::new));
        Set<User> treeSet = list.stream().collect(Collectors.toCollection(TreeSet::new));
        System.out.println("LinkedList:" + linkedList);
        System.out.println("CopyOnWriteArrayList:" + copyOnWriteArrayList);
        System.out.println("TreeSet:" + treeSet);

        System.out.println("【常用】直接返回:Collectors.toXXX()");
        List<User> list1 = list.stream().collect(Collectors.toList());
        Set<User> set = list.stream().collect(Collectors.toSet());
        Map<Integer, String> map = list.stream().collect(Collectors.toMap(User::getId, User::getName));
        System.out.println("toList:" + list1);
        System.out.println("toSet():" + set);
        System.out.println("toMap():" + map);
    }
}

Results of the

 

6. Reference

How to solve the problem of cannot be cast to java.lang.Comparable? _msg1_'s blog-CSDN blog

Guess you like

Origin blog.csdn.net/ladymorgana/article/details/133079993