1. 程式人生 > >Java8 Stream 歸約 使用示例

Java8 Stream 歸約 使用示例

package com.expgiga.Java8;

/**
 *
 */
public class Employee {
    private String name;
    private int age;
    private double salary;
    private int id;

    private Status status;

    public Employee() {
    }

    public Employee(String name, int age, double salary) {
        this.name = name;
        this
.age = age; this.salary = salary; } public Employee(String name, int age, double salary, Status status) { this.name = name; this.age = age; this.salary = salary; this.status = status; } public String getName() { return name; } public void
setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } @Override
public String toString() { return "Employee{" + "name='" + name + '\'' + ", age=" + age + ", salary=" + salary + ", id=" + id + ", status=" + status + '}'; } public Employee(int id) { this.id = id; } public Employee(int id, int age) { this.id = id; this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Employee employee = (Employee) o; if (age != employee.age) return false; if (Double.compare(employee.salary, salary) != 0) return false; if (id != employee.id) return false; return name != null ? name.equals(employee.name) : employee.name == null; } @Override public int hashCode() { int result; long temp; result = name != null ? name.hashCode() : 0; result = 31 * result + age; temp = Double.doubleToLongBits(salary); result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + id; return result; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public enum Status { FREE, BUSY, VOCATION; } }

package com.expgiga.Java8;

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

/**
 * Java8 Stream的終止操作:
 */
public class TestStreamAPI {
    public static void main(String[] args) {
        /*
         * 查詢與匹配          * allMatch
          * anyMatch
          * noneMatch
          * findFirst
          * findAny
          * count
          * max
          * min
          *
         */
List<Employee> employeeList = Arrays.asList(
                new Employee("zhangsan", 18, 19999, Employee.Status.FREE),
                new Employee("lisi", 28, 29999, Employee.Status.BUSY),
                new Employee("wangwu", 38, 39999, Employee.Status.VOCATION),
                new Employee("zhaoliu", 16, 17999, Employee.Status.BUSY),
                new Employee("tianqi", 6, 12999, Employee.Status.FREE),
                new Employee("tianqi", 6, 12999, Employee.Status.FREE)
        );

        /*
         * 歸約         * reduce
         */
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Integer sum = list.stream()
                .reduce(0, (x, y) -> x + y);
        System.out.println(sum);

        System.out.println("-----------------------------------------------");

        Optional<Double> op = employeeList.stream() //可能為空 所有返回的是Optional
.map(Employee::getSalary)
                .reduce(Double::sum);
        System.out.println(op.get());

        /*
         * 收集         * collect
         */
List<String> list2 = employeeList.stream()
                .map(Employee::getName)
                .collect(Collectors.toList());
        list2.forEach(System.out::println);

        Set<String> set = employeeList.stream()
                .map(Employee::getName)
                .collect(Collectors.toSet());
        set.forEach(System.out::println);

        System.out.println("-----------------------------------------------");

        HashSet<String> hs = employeeList.stream()
                .map(Employee::getName)
                .collect(Collectors.toCollection(HashSet::new));
        hs.forEach(System.out::println);

        //總數
Long count = employeeList.stream()
                .collect(Collectors.counting());
        System.out.println(count);

        //平均值
Double avg = employeeList.stream()
                .collect(Collectors.averagingDouble(Employee::getSalary));
        System.out.println(avg);

        //總和
Double sumSalary = employeeList.stream()
                .collect(Collectors.summingDouble(Employee::getSalary));
        System.out.println(sumSalary);

        //最大值
Optional<Employee> max = employeeList.stream()
                .collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
        System.out.println(max.get());

        //最小值
Optional<Double> min = employeeList.stream()
                .map(Employee::getSalary)
                .collect(Collectors.minBy(Double::compare));
        System.out.println(min.get());


        //分組
Map<Employee.Status, List<Employee>> map = employeeList.stream()
                .collect(Collectors.groupingBy(Employee::getStatus));
        System.out.println(map);

        //多級分組
Map<Employee.Status, Map<String, List<Employee>>> mapMap = employeeList.stream()
                .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
                    if (((Employee)e).getAge() <= 18) {
                        return "dud";
                    } else if(((Employee)e).getAge() <= 30) {
                        return "heh";
                    } else {
                        return "hah";
                    }
                })));
        System.out.println(mapMap);

        //分片(分割槽)
Map<Boolean, List<Employee>> booleanListMap = employeeList.stream()
                .collect(Collectors.partitioningBy((e) -> e.getSalary() > 13000));
        System.out.println(booleanListMap);

        //其他
DoubleSummaryStatistics dss = employeeList.stream()
                .collect(Collectors.summarizingDouble(Employee::getSalary));
        System.out.println(dss.getSum());

        String str = employeeList.stream()
                .map(Employee::getName)
                .collect(Collectors.joining());
        System.out.println(str);
    }
}