Java8 new characteristic flow data processing

Source: Internet
Author: User

Flow Intermediate operation

Operation type return type Operating Parameters function Descriptor
Filter Middle Stream predicate Boolean, T
Map Middle Stream Function<t,r> T-R
Limit Middle Stream
Sorted Middle Stream Comparator int (T, t)
Distinct Middle Stream
FlatMap Middle Stream Function<t, Stream T-Stream
Terminal operations
Operation type return type Operating Parameters function Descriptor
Foreach Terminal void Consumer T-Void
Count Terminal Long
Collect Terminal R Collector<t, A,r>
AnyMatch Terminal Boolean predicate Boolean, T
Allmatch Terminal Boolean predicate< t> Boolean, T
Nonematch Terminal Boolean predicate Boolean, T
Findany Terminal Optional
FindFirst Terminal Optional
Reduce Terminal Optional Binaryoperator T (t, T)



Action Start Initialization
@Data@AllArgsConstructorpublic class Employee implements Serializable {   private static final long serialVersionUID = -8078550089934349371L;   private Long id;   /**    * 姓名    */   private String name;   /**    * 年龄    */   private Integer age;   /**    * 部门    */   private String department;   /**    * 专业    */   private String profession;   /**    * 地址    */   private String Address;}
public static List<Employee> employees = Collections.unmodifiableList(Arrays.asList(   new Employee(1L, "张三", 18, "技术开发中心", "计算机科学", "江西南昌"),   new Employee(2L, "李四", 18, "技术开发中心", "计算机科学", "江西抚州"),   new Employee(3L, "王五", 22, "人力行政中心", "土木工程", "北京"),   new Employee(4L, "赵六", 23, "财务管理中心", "经济管理", "广东广州"),   new Employee(5L, "田七", 28, "财务管理中心", "机械与自动化", "上海"),   new Employee(5L, "田七", 28, "财务管理中心", "机械与自动化", "上海"),   new Employee(6L, "孔明", 26, "战略合作事业部", "生化工程", "广东深圳"),   new Employee(7L, "玄德", 40, "战略合作事业部", "生命科学", "江苏南京"),   new Employee(8L, "云长", 33, "客户服务部", "社会学", "广东广州"),   new Employee(9L, "翼德", 28, "智能金融事业部", "经济管理", "江苏南京"),   new Employee(10L, "鲁肃", 36, "智能金融事业部", "经济管理", "上海")));

1.0 Filtration

    • Filter Filters employees younger than 25

      List<Employee> list = employees.stream()          .filter(employee -> employee.getAge() > 25)          .collect(Collectors.toList());
    • distinct filtering repeating elements

      List<Employee> list = employees.stream()            .filter(employee -> employee.getAge() > 25)            .distinct()            .collect(Collectors.toList());
    • Limit Cutoff

List<Employee> list = employees.stream()           .filter(employee -> employee.getAge() > 25)           .limit(3)           .collect(Collectors.toList());
    • ? Skip Skipping elements
List<Employee> list = employees.stream()               .filter(employee -> employee.getAge() > 25)               .skip(2)               .collect(Collectors.toList());

2.0 Mapping

    • map Get the names of all employees

      List<String> list = employees.stream()          .map(Employee::getName)          .collect(Collectors.toList());
    • FlatMap Flat Flow

      String[] arrays = {"Hello", "World"};List<String> list = Arrays.stream(arrays)            .map(str -> str.split("")) // 映射成为Stream<String[]>            .flatMap(Arrays::stream) // 扁平化为Stream<String>            .distinct()            .collect(Collectors.toList());

3.0 Finding and matching

  • Whether an element in the AnyMatch stream can match the given predicate returns a Boolean

    boolean result = employees.stream()         .anyMatch(employee -> employee.getAge() == 28);
  • Whether all elements in the Allmatch stream Meet the criteria

     boolean result = employees.stream()         .allMatch(employee -> employee.getAge() < 35);
  • Nonematch can ensure that no element in the stream matches the given predicate

    boolean result = employees.stream()       .noneMatch(employee -> employee.getAge() > 40);
  • findany returns any element in the current stream

    Optional<Employee> result = employees.stream()           .filter(employee -> Objects.equals(employee.getProfession(), "计算机科学"))           .findAny();
  • FindFirst Returns the first element in the current stream

    Optional<Employee> result = employees.stream()           .filter(employee -> Objects.equals(employee.getProfession(), "计算机科学"))           .findFirst();

    You might wonder, why do you have FindFirst and Findany at the same time? The answer is parallel. Find the first element to limit more in parallel. If you don't care which element is returned, use findany because it has fewer restrictions when using parallel streams.

4.0 Attribution

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);// 计算数值总合// 方式一Integer result1 = numbers.stream().reduce(0, (a, b) -> a + b);// 方式二Integer result2 = numbers.stream().reduce(0, Integer::sum);// 计算最大值Optional<Integer> min = numbers.stream().reduce(Integer::min);// 计算最小值Optional<Integer> min = numbers.stream().reduce(Integer::max);

5.0 Collectors

    • Eg: Calculate the total number of employees
long count = employees.stream().count();Long count = employees.stream().collect(Collectors.counting());
    • Eg: Find the oldest employee in the

      Optional<Employee> employee = employees.stream()          .collect(Collectors.maxBy(Comparator.comparing(Employee::getAge)));Optional<Employee> employee = employees.stream()             .max(Comparator.comparing(Employee::getAge));
    • Eg: Employee Age summary

      Integer sum = employees.stream()          .mapToInt(Employee::getAge).sum();Integer sum = employees.stream()          .collect(Collectors.summingInt(Employee::getAge));
    • Eg: employee average

      Double averaging = employees.stream().collect(Collectors.averagingInt(Employee::getAge))

6.0 Grouping

    • Eg: employees are grouped by profession

      Map<String, List<Employee>> map = employees.stream()          .collect(Collectors.groupingBy(Employee::getProfession));
    • Eg: employees are grouped by profession and the number of professionals is counted

      Map<String, Long> map = employees.stream()          .collect(Collectors.groupingBy(Employee::getProfession, Collectors.counting()));
    • Eg: Group by specialty and find the oldest person in the profession

 Map<String, Optional<Employee>> map = employees.stream().collect(           Collectors.groupingBy(Employee::getProfession,                                                          Collectors.maxBy(Comparator.comparing(Employee::getAge))));
    • Eg: converting collector results to another type Collectors.collectingandthen

      Map<String, Employee> map = employees.stream().collect( Collectors.groupingBy(Employee::getProfession,Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Employee::getAge)),Optional::get)));
    • Eg: mapping collectors to specific objects

      Map<String, Set<Integer>> map = employees.stream().collect(          Collectors.groupingBy(Employee::getProfession, Collectors.mapping(Employee::getAge, Collectors.toSet())));

      ?

Java8 new characteristic flow data processing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.