Lambda使用Stream包下的Collectors的入门案例【第一篇】

源码中的案例

/**
 * Implementations of {@link Collector} that implement various useful reduction
 * operations, such as accumulating elements into collections, summarizing
 * elements according to various criteria, etc.
 *
 * <p>The following are examples of using the predefined collectors to perform
 * common mutable reduction tasks:
 *
 * <pre>{@code
 *     // Accumulate names into a List
 *     List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());
 *
 *     // Accumulate names into a TreeSet
 *     Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new));
 *
 *     // Convert elements to strings and concatenate them, separated by commas
 *     String joined = things.stream()
 *                           .map(Object::toString)
 *                           .collect(Collectors.joining(", "));
 *
 *     // Compute sum of salaries of employee
 *     int total = employees.stream()
 *                          .collect(Collectors.summingInt(Employee::getSalary)));
 *
 *     // Group employees by department
 *     Map<Department, List<Employee>> byDept
 *         = employees.stream()
 *                    .collect(Collectors.groupingBy(Employee::getDepartment));
 *
 *     // Compute sum of salaries by department
 *     Map<Department, Integer> totalByDept
 *         = employees.stream()
 *                    .collect(Collectors.groupingBy(Employee::getDepartment,
 *                                                   Collectors.summingInt(Employee::getSalary)));
 *
 *     // Partition students into passing and failing
 *     Map<Boolean, List<Student>> passingFailing =
 *         students.stream()
 *                 .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
 *
 * }</pre>
 *
 * @since 1.8
 */

源码中的代码案例解析

package com.lambda.lambdademo.test_la_01;

import com.lambda.lambdademo.domain.Employee;
import com.lambda.lambdademo.domain.People;
import com.lambda.lambdademo.domain.Student;
import org.junit.jupiter.api.Test;

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

/**
 * @date :2019-12-13 16:31
 * @description:
 */
public class CollectorTest {

    private static final Integer PASS_THRESHOLD = 6;

    private List<People> getPeopleList(){
        List<People> pList = new ArrayList<>();
        pList.add(new People(1, "lisi"));
        pList.add(new People(2, "wangwu"));
        pList.add(new People(3, "maliu"));
        pList.add(new People(4, "maliu"));
        return pList;
    }

    private List<Employee> getEmployeeList(){
        List<Employee> eList = new ArrayList<>();
        eList.add(new Employee(1, "lisi", "test"));
        eList.add(new Employee(2, "wangwu", "dev"));
        eList.add(new Employee(3, "maliu", "ceo"));
        eList.add(new Employee(3, "maliu", "ceo"));
        return eList;
    }

    private List<Student> getStudentList(){
        List<Student> sList = new ArrayList<>();
        sList.add(new Student(1, "lisi", 5));
        sList.add(new Student(2, "wangwu", 7));
        sList.add(new Student(3, "maliu", 9));
        return sList;
    }

    /**
     * 官方测试案例
     * @see Collectors
     */
    @Test
    public void test_all(){
        List<People> peopleList = getPeopleList();
        /**
         * new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
         *                                    (left, right) -> { left.addAll(right); return left; },
         *                                    CH_ID)
         *                                    TODO 底层实现转换的是ArrayList
         */
        List<String> collect = peopleList.stream().map(People::getName).peek(System.out::println).collect(Collectors.toList());
        collect.forEach(s -> System.out.println("ArrayList : " + s));

        /**
         * new CollectorImpl<>((Supplier<Set<T>>) HashSet::new, Set::add,
         *                                    (left, right) -> { left.addAll(right); return left; },
         *                                    CH_UNORDERED_ID)
         *                                    TODO 底层实现转换的是HashSet
         */
        Set<String> collect1 = peopleList.stream().map(People::getName).peek(System.out::println).collect(Collectors.toSet());
        collect1.forEach(s -> System.out.println("HashSet : " + s));

        /**
         * TODO 这个是 TreeSet
         */
        TreeSet<String> collect2 = peopleList.stream().map(People::getName).peek(System.out::println).collect(Collectors.toCollection(TreeSet::new));
        collect2.forEach(s -> System.out.println("TreeSet : " + s));

        /**
         * 将集合转换为逗号分隔的元素
         * 以下者两个方法都可以
         */
        String join = String.join(",", collect);
        System.out.println("join : " + join);// lisi,wangwu,maliu,maliu

        /**
         * new CollectorImpl<CharSequence, StringBuilder, String>(
         *                 StringBuilder::new, StringBuilder::append,
         *                 (r1, r2) -> { r1.append(r2); return r1; },
         *                 StringBuilder::toString, CH_NOID)
         */
        String collect3 = collect.stream().map(String::toString).collect(Collectors.joining(","));
        System.out.println("collect3 : " + collect3);// lisi,wangwu,maliu,maliu

        /**
         * joining(delimiter, "", "")
         *  TODO 从源码调的是下面的这个方法
         */
        String collect4 = collect.stream().map(String::toString).collect(Collectors.joining());
        System.out.println("collect4 : " + collect4); // lisiwangwumaliumaliu

        /**
         * new CollectorImpl<>(
         *                 () -> new StringJoiner(delimiter, prefix, suffix),
         *                 StringJoiner::add, StringJoiner::merge,
         *                 StringJoiner::toString, CH_NOID);
         */
        String collect5 = collect.stream().map(String::toString).collect(Collectors.joining(",", "", ""));
        System.out.println("collect5 : " + collect5); // lisi,wangwu,maliu,maliu

        /**
         * 计算所有员工的工资总合
         */
        List<Employee> employeeList = getEmployeeList();
        /**
         * 方法一
         * new CollectorImpl<>(
         *                 () -> new int[1],
         *                 (a, t) -> { a[0] += mapper.applyAsInt(t); },
         *                 (a, b) -> { a[0] += b[0]; return a; },
         *                 a -> a[0], CH_NOID);
         *                 TODO 返回一个Collector,有元素就是所有整数元素的和
         *                  如果没有任何元素则返回0
         */

        int collect6 = employeeList.stream().collect(Collectors.summingInt(Employee::getSalary));
        // 方法二: 对方法一的优化
        int collect6_ = employeeList.stream().mapToInt(Employee::getSalary).sum();
        System.out.println("方法一: " + collect6);
        System.out.println("方法二: " + collect6_);

        /**
         * 根据部门名称进行分配,key 为部门 value 为该部门的员工
         */
        Map<String, List<Employee>> map = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment));
        for (String s : map.keySet()) {
            System.out.println("====== key: " + s + "  =====value: " + map.get(s));
        }

        /**
         * 根据部门名称进行分配,key 为部门 value 为该部门的员工薪资的总和
         */
        Map<String, Integer> map1 = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment, Collectors.summingInt(Employee::getSalary)));
        for (String s : map1.keySet()) {
            System.out.println("====== key: " + s + "  =====value: " + map1.get(s));
        }

        /**
         * 根据部门名称进行分配,key 为部门 value 为该部门的员工的个数
         */
        Map<String, Long> map1_ = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));
        for (String s : map1_.keySet()) {
            System.out.println("====== key: " + s + "  =====value: " + map1_.get(s));
        }

        /**
         * 根据年龄是否大于6进行分配
         * 大于6 true
         * 小于6 false
         * key 是否大于6的布尔值 value 为学生集合
         */
        List<Student> studentList = getStudentList();
        Map<Boolean, List<Student>> listMap = studentList.stream().collect(Collectors.partitioningBy(student -> student.getAge() >= PASS_THRESHOLD));
        for (Boolean aBoolean : listMap.keySet()) {
            System.out.println("====== key: " + aBoolean + "  =====value: " + listMap.get(aBoolean));
        }

    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wildwolf_001/article/details/103550187