Java 8: Stream API stream operation (learning)

Java 8:Stream API

The Stream API in Java 8 is a set of new features for processing collection data; it provides a way to operate collections in a declarative style, simplifying the processing of collections, making the code more concise, elegant, and more efficient Processing data;
this style regards the set of elements to be processed as a stream, which is transmitted in the pipeline and can be processed on the nodes of the pipeline, such as filtering, sorting, aggregation, etc.; the element stream undergoes intermediate operations in the pipeline (intermediate operation) processing, and finally the final operation (terminal operation) to get the result of the previous processing

characteristic

Declarative programming style: Stream API provides a declarative programming approach similar to SQL queries, which operate on data by calling a series of methods in a chain instead of explicitly writing loops or temporary variables. This makes the code more concise, readable and understandable

Lazy evaluation: Stream is lazy evaluated, that is, it will only be executed when the operation is terminated; intermediate operations (such as filter, map, sorted, etc.) only define the processing steps of the data stream, and will not be executed immediately; this can Optimize processing to avoid unnecessary calculations and improve performance

Functional interface support: Stream API needs to be used with a functional interface (Functional Interface); a functional interface is an interface that contains only one abstract method, and a Lambda expression can be passed as an instance of a functional interface; this support makes the Stream API Ability to take full advantage of functional programming

generate flow

In Java 8, the collection interface has two methods to generate streams:

  1. stream(): Create a serial stream for a collection
  2. parallelStream() − : creates a parallel stream for a collection
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

The strings list creates a stream, and the list is converted into a stream through the stream() method; then, the filter method is used to pass a Lambda expression to filter (filter) elements that do not meet the conditions; here, the Lambda expression string -> !string.isEmpty() checks whether the string is not empty; only if the string is not empty, the element will be kept in the stream; finally, using the collect method, combined with the Collectors.toList() collector, will conform to The elements of the condition are collected into a new list filtered

streaming operation

  • forEach

Stream provides a new method forEach to iterate each data in the stream: the following code snippet uses forEach to output 10 random numbers: The
ints() method is used to generate an infinite stream of random integers

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
  • map

The map method is used to map each element to the corresponding result: the following code snippet uses map to output the square number corresponding to the element

 List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 获取对应的平方数
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
  • filter

The filter method is used to filter out elements through the set conditions: the following code snippet uses the filter method to filter out empty strings

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
long count = strings.stream().filter(string -> string.isEmpty()).count();
  • limit

The limit method is used to obtain the specified number of streams: the following code fragment uses the limit method to print out 10 pieces of data

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
  • sorted

The sorted method is used to sort the stream: The following code snippet uses the sorted method to sort the output of 10 random numbers

Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);
  • parallel program

parallelStream is an alternative to stream parallel handlers: in the following example we use parallelStream to output the number of empty strings

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
long count = strings.parallelStream().filter(string -> string.isEmpty()).count();
  • Collectors

The Collectors class implements many reduction operations, such as converting streams into collections and aggregating elements: Collectors can be used to return lists or strings

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
 
System.out.println("筛选列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);
  • statistics

Collectors that generate statistical results; they are mainly used for basic types such as int, double, and long, and they can be used to generate statistical results similar to the following

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
 
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
 
System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());
  • map operation

Three common map operations in Stream API: map, mapToInt and flatMap

  • map: Used to map elements in a stream to another type of stream. For example, mapping each object in an object stream to a stream composed of a certain attribute value of the object
  • mapToInt: used to map the elements in the stream to IntStream, that is, the stream of the basic type int. It is commonly used to map elements in a stream to integer values
  • flatMap: Used to map each element in a stream into a stream, and then concatenate these streams into a single stream. It is often used to flatten nested stream structures
  • the case
systemApplicationTypeRepo.list(new QueryWrapper<SystemApplicationType>().orderByAsc(SystemApplicationTypeCol.ID))
                .stream().map(bean -> new ResCommonIdNameCode(bean.getId(), bean.getName(), bean.getName())).collect(Collectors.toList()

systemApplicationTypeRepo.list(…) : This part of the code uses a warehouse (Repository) named systemApplicationTypeRepo to query the data in the database by calling the list method; the list method accepts a query condition object QueryWrapper as a parameter to specify the query condition

new QueryWrapper().orderByAsc(SystemApplicationTypeCol.ID) : This is the process of creating a query condition object; QueryWrapper is a tool provided by MyBatis-Plus for building query conditions; orderByAsc(SystemApplicationTypeCol.ID) means according to the ID in the SystemApplicationType entity class The fields are sorted in ascending order.

.stream() : This converts the query result into a Stream object for subsequent operations

.map(bean -> new ResCommonIdNameCode(bean.getId(), bean.getName(), bean.getName())) : This part uses the map operation to map each SystemApplicationType object of the query result to a ResCommonIdNameCode object; ResCommonIdNameCode is a A custom class, the constructor accepts id, name and code as parameters to create a new object

.collect(Collectors.toList()) : Finally, use the collect method to collect the Stream object as a List, which is the final result list

noticeResponses.stream()
                .sorted(Comparator.comparing(SystemNoticeResponse::getReadStatus)
                        .thenComparing(Comparator.comparing(SystemNoticeResponse::getCreateAt).reversed()))
                .collect(Collectors.toList());

.stream() : Convert the list of noticeResponses into a Stream object, enabling it to use the operations provided by the Stream API

.sorted(…) : This is an intermediate operation for sorting the elements in the stream; use the Comparator.comparing(…) method to create a comparator to specify the sorting rules; first, according to the readStatus field of the SystemNoticeResponse object Sort in ascending order; .thenComparing(…) means that if the readStatus is the same, sort in descending order according to the createAt field (using the reversed() method)

. collect(Collectors.toList()) : Finally, use the collect method to collect the sorted Stream objects into a new List, which is the sorted noticeResponses list

Guess you like

Origin blog.csdn.net/mcband/article/details/132526572