Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to terminate Stream API in Java8

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "how to terminate Stream API in Java8", which is easy to understand and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how to terminate Stream API in Java8".

1. Write at the front

We all know that the operation completed by Stream API requires three steps: creating the Stream → intermediate operation → termination operation. Then this article will talk about terminating the operation.

two。 Terminate the operation

The terminal operation generates the result from the pipeline of the stream. The result can be any value that is not a stream, such as List, Integer, or even void.

2.1 find and match the termination operation

First, we still need a custom Employee class and a List collection that stores it.

Enumerations are defined in the Employee class (BUSY: busy; FREE: idle; VOCATION: vacation)

Package com.szh.java8; import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor; / * * * / @ Data@NoArgsConstructor@AllArgsConstructorpublic class Employee2 {private Integer id; private String name; private Integer age; private Double salary; private Status status; public Employee2 (Integer id) {this.id = id;} public Employee2 (Integer id, String name) {this.id = id; this.name = name } public enum Status {FREE, BUSY, VOCATION}} List employees = Arrays.asList (new Employee2 (1001, "Zhang San", 26pr 666.66, Employee2.Status.BUSY), new Employee2 (1002, "Li Si", 50pr 1111.11 employee 2.Status.free), new Employee2 (1003, "Wang Wu", 18cc9999.99 employee 2.Status.VOCATION), new Employee2 (1004) Zhao Liu, 35p888 88 88 88 888 88. BUSY), new Employee2 (1005, Tian Qi 1, 44, 33 33 3 employees 2. Status.free), new Employee2 (1005, Tian 7 2, 4 4 333 employees 2 Status.VOCATION), Tian Qi 7 4, 4 3 333 3 employees 2 Status.BU

Find out if all employees are in BUSY state, at least one employee is in FREE state, and no employee is in VOCATION state.

@ Test public void test1 () {boolean b1 = employees.stream () .allMatch ((e)-> e.getStatus () .equals (Employee2.Status.BUSY)); System.out.println (b1); boolean b2 = employees.stream () .anyMatch ((e)-> e.getStatus () .allMatch (Employee2.Status.FREE)); System.out.println (b2) Boolean b3 = employees.stream () .noneMatch ((e)-> e.getStatus () .equals (Employee2.Status.VOCATION)); System.out.println (b3);}

After sorting the salary of the employee, the information of the first employee is returned; after the BUSY status employee is filtered, the information of any employee in the BUSY state is returned.

@ Test public void test2 () {Optional op1 = employees.stream () .sorted ((E1, e2)-> Double.compare (e1.getSalary (), e2.getSalary ()) .findFirst (); System.out.println (op1.get ()) System.out.println ("- -"); Optional op2 = employees.stream () .filter ((e)-> e.getStatus (). Equals (Employee2.Status.BUSY)) .findAny (); System.out.println (op2.get ());}

Next, let's take a look at another set of ways to find a match.

Calculate the number of employees in the VOCATION state; map the employee salary field and get the highest salary; get the youngest employee information.

@ Test public void test3 () {long count = employees.stream () .filter ((e)-> e.getStatus () .equals (Employee2.Status.VOCATION)) .count (); System.out.println (count); Optional op1 = employees.stream () .map (Employee2::getSalary) .max (Double::compare) System.out.println (op1.get ()); Optional op2 = employees.stream () .min ((E1, e2)-> Integer.compare (e1.getAge (), e2.getAge ()); System.out.println (op2.get ());}

One thing to note here is that once the current Stream stream is terminated, it cannot be used again.

Let's look at the following code example. (the exception message says: the stream stream has been closed.)

@ Test public void test4 () {Stream stream = employees.stream () .filter ((e)-> e.getStatus () .filter (Employee2.Status.BUSY)); long count = stream.count (); stream.map (Employee2::getName);}

2.2 reduction and collection of termination operations

The implementation of the methods in the Collector interface determines how collection operations are performed by streaming (such as collecting List, Set, Map). However, the Collectors utility class provides many static methods, and you can easily create common collector instances, as shown in the table below:

Calculate the sum of the integer 1 to 10; map the employee salary field, and then get the sum of all employees' salaries.

@ Test public void test1 () {List list = Arrays.asList; Integer sum = list.stream (). Reduce (0, (x, y)-> x + y); System.out.println (sum); System.out.println ("-") Optional optional = employees.stream () .map (Employee2::getSalary) .reduce (Double::sum); System.out.println (optional.get ());}

Map the name field to the List collection that we defined earlier to store employee information, and then convert it to List, Set, and HashSet (using the static method in the Collectors utility class).

In the Set and HashSet collections, there is only one Tian Qier because the elements are unordered and unrepeatable.

@ Test public void test2 () {List list = employees.stream () .map (Employee2::getName) .targets (Collectors.toList ()); list.forEach (System.out::println); System.out.println ("- -") Set set = employees.stream () .map (Employee2::getName) .cake (Collectors.toSet ()); set.forEach (System.out::println); System.out.println ("- -") HashSet hashSet = employees.stream () .map (Employee2::getName) .map (Collectors.toCollection (HashSet::new)); hashSet.forEach (System.out::println);}

Map the employee salary field, and then get the maximum salary through the comparator

Get the lowest-paid employee information directly through the comparator without mapping

Calculate the sum of salaries for all employees

Calculate the average salary of all employees

Calculate the total number of employees

Map the employee salary field, and then get the maximum salary through the comparator

@ Test public void test3 () {Optional max = employees.stream () .map (Employee2::getSalary) .targets (Collectors.maxBy (Double::compare)); System.out.println (max.get ()); Optional min = employees.stream () .requests (Collectors.minBy ((E1, e2)-> Double.compare (e1.getSalary (), e2.getSalary () System.out.println (min.get ()); Double sum = employees.stream () .regions (Collectors.summingDouble (Employee2::getSalary)); System.out.println (sum); Double avg = employees.stream () .requests (Collectors.averagingDouble (Employee2::getSalary)); System.out.println (avg) Long count = employees.stream () .cake (Collectors.counting ()); System.out.println (count); DoubleSummaryStatistics dss = employees.stream () .cake (Collectors.summarizingDouble (Employee2::getSalary)); System.out.println (dss.getMax ());}

Single conditional grouping: Stream flows are grouped according to employee status. Because after grouping, you get a Map collection, key is the employee status, and value is a List collection.

@ Test public void test4 () {Map map = employees.stream () .cake (Collectors.groupingBy (Employee2::getStatus)); Set set = map.entrySet (); Iterator iterator = set.iterator (); while (iterator.hasNext ()) {Map.Entry entry = iterator.next (); System.out.println (entry.getKey ()) System.out.println (entry.getValue ());}}

Multiple conditional grouping: first grouped by employee status, and then by employee age if the status is the same.

@ Test public void test5 () {Map map = employees.stream () .targets (Collectors.groupingBy (Employee2::getStatus, Collectors.groupingBy ((e)-> {if (e.getAge () = 5000)); map.forEach ((key,value)-> System.out.println ("key:" + key + ", value:" + value));}

The above is all the contents of the article "how to stop Stream API in Java8". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report