测试Stream的终止操作
package com.atguigu.java3;
import com.atguigu.java2.Employee;
import com.atguigu.java2.EmployeeData;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamTest2 {
@Test
public void test1() {
List<Employee> employees = EmployeeData.getEmployees();
boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);
System.out.println(allMatch);
boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 10000);
System.out.println(anyMatch);
boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("雷"));
System.out.println(noneMatch);
Optional<Employee> employee = employees.stream().findFirst();
System.out.println(employee);
Optional<Employee> employee1 = employees.parallelStream().findAny();
System.out.println(employee1);
}
@Test
public void test2() {
List<Employee> employees = EmployeeData.getEmployees();
long count = employees.stream().filter(e -> e.getSalary() > 5000).count();
System.out.println(count);
Stream<Double> salary = employees.stream().map(e -> e.getSalary());
Optional<Double> aDouble = salary.max(Double::compare);
System.out.println(aDouble);
Optional<Employee> employee = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(employee);
employees.stream().forEach(System.out::println);
}
@Test
public void test3() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer sum = list.stream().reduce(0, Integer::sum);
System.out.println(sum);
List<Employee> employees = EmployeeData.getEmployees();
Stream<Double> salary = employees.stream().map(Employee::getSalary);
Optional<Double> aDouble = salary.reduce(Double::sum);
System.out.println(aDouble);
}
@Test
public void test4() {
List<Employee> list = EmployeeData.getEmployees();
List<Employee> list1 = list.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList());
list1.forEach(System.out::println);
Set<Employee> set = list.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());
set.forEach(System.out::println);
}
}