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

Analysis of Stream API Terminal Operation example of java

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

Share

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

This article mainly introduces "java Stream API terminal operation example analysis". In daily operation, I believe many people have doubts about java Stream API terminal operation example analysis. Xiaobian consulted all kinds of materials and sorted out simple and easy to use operation methods. I hope to help you answer the doubts of "java Stream API terminal operation example analysis"! Next, please follow the small series to learn together!

Java Stream pipeline data processing operations

In the previous articles written in this issue, I have introduced you to Java Stream pipeline flow, which is a java API used to simplify the processing of collection class elements. There are three stages in the process of use. Before I start this article, I feel I still need to introduce some new friends to these three stages, as shown in the figure:

Phase 1 (blue): Convert a collection, array, or line text file to a java Stream pipeline stream

Stage 2 (dotted line): Pipeline streaming data processing operations, processing each element in the pipeline. The output element from the previous pipe acts as the input element for the next pipe.

Stage 3 (green): Pipeline flow result processing operations, which is the core of this article.

Before we begin, it is still necessary to recall an example we gave you earlier:

List nameStrs = Arrays.asList("Monkey", "Lion", "Giraffe","Lemur");List list = nameStrs.stream() .filter(s -> s.startsWith("L")) .map(String::toUpperCase) .sorted() .collect(toList());System.out.println(list);

First use the stream() method to convert the string List to a pipeline stream

The pipeline data processing operation is then performed by filtering all strings starting with an upper L with the fliter function, converting the strings in the pipeline to upper letters toUpperCase, and then calling the sorted method for sorting. The usage of these APIs was described in previous articles. Lambda expressions and function references are also used.

Finally, use the collect function to process the result, converting the java Stream pipeline stream to a List. The output of the final list is:[LEMUR, LION]

Think about how many lines of code you would need to do this if you didn't use java Stream pipelining. Back to the topic, this article is to introduce you to the third stage: what can be done to the pipeline flow processing results? Let's get started!

ForEach and ForEachOrdered

If we just want to print out the results of processing the Stream pipeline stream, rather than type conversion, we can use the forEach() method or forEachOrdered() method.

Stream.of("Monkey", "Lion", "Giraffe", "Lemur", "Lion") .parallel() .forEach(System.out::println);Stream.of("Monkey", "Lion", "Giraffe", "Lemur", "Lion") .parallel() .forEachOrdered(System.out::println);

The parallel() function indicates that the elements in the pipeline are processed in parallel rather than serially, which is faster. However, this may lead to the later elements in the pipeline flow being processed first, and the previous elements being processed later, that is, the order of the elements cannot be guaranteed.

ForEachOrdered is understandable from the name, although it may not be guaranteed in the order of data processing, but forEachOrdered method can guarantee that the order of elements output is consistent with the order in which elements enter the pipeline flow. This is what it looks like (the forEach method doesn't guarantee this order):

Monkey

Lion

Giraffe

Lemur

Lion

III. Collection of elements

The most common uses of java Stream are: converting a collection class into a pipeline stream, processing the pipeline stream data, and converting the pipeline stream processing result into a collection class. The collect() method then provides us with the ability to convert the pipeline flow processing result into a collection class.

3.1. Collected for Set

Collect the processing results of Stream through Collectors.toSet() method, collecting all elements into Set collection.

Set collectToSet = Stream.of( "Monkey", "Lion", "Giraffe", "Lemur", "Lion") .collect(Collectors.toSet());//The elements in the final collectToSet are:[Monkey, Lion, Giraffe, Lemur], note that the Set is de-weighted. 3.2. Collected List

Similarly, elements can be collected into a List collector using toList().

List collectToList = Stream.of( "Monkey", "Lion", "Giraffe", "Lemur", "Lion").collect(Collectors.toList());//The elements in the final collectToList are: [Monkey, Lion, Giraffe, Lemur, Lion]3.3.

The element collection methods introduced above are all dedicated. For example, Collectors.toSet() is used to collect a Set type collection; Collectors.toList() is used to collect a List type collection. So, is there a more general way to collect data elements, collecting data into arbitrary Collection interface subtypes? So, here is a generic way to collect elements, as you can collect data elements into any Collection type: a way to provide constructors to the desired Collection type.

LinkedList collectToCollection = Stream.of( "Monkey", "Lion", "Giraffe", "Lemur", "Lion").collect(Collectors.toCollection(LinkedList::new));//elements in final collectToCollection are: [Monkey, Lion, Giraffe, Lemur, Lion]

Note: LinkedList::new is used in the code, which actually calls the LinkedList constructor to collect elements into Linked List. Of course, you can also use LinkedHashSet::new and PriorityQueue::new to collect data elements into other collection types, which is more generic.

3.4. Collected Array

The toArray(String[]::new) method collects the processing results of Stream, collecting all elements into a string array.

String[] toArray = Stream.of( "Monkey", "Lion", "Giraffe", "Lemur", "Lion") .toArray(String[]::new);//The elements in the final toArray string array are: [Monkey, Lion, Giraffe, Lemur, Lion]3.5. Collected Map

Use Collectors.toMap() method to collect data elements into Map, but there is a question: whether the elements in the pipeline are as keys or values. We use a Function.identity() method that simply returns a " t -> t "(lambda expression whose input is the output). The pipe flow handler distinct() is also used to ensure uniqueness of Map keys.

Map toMap = Stream.of( "Monkey", "Lion", "Giraffe", "Lemur", "Lion").distinct().collect(Collectors.toMap( Function.identity(), //element input is output as key s -> (int) s.chars().distinct().count()//Enter the number of different letters of the element as value));//The final toMap result is: {Monkey=6, Lion=4, Lemur=5, Giraffe=6}3.6. GroupingBy

Collectors.groupingBy is used to collect elements in groups. The following code demonstrates how to collect different data elements into different Lists according to their initials and encapsulate them into Maps.

Map groupingByList = Stream.of( "Monkey", "Lion", "Giraffe", "Lemur", "Lion").collect(Collectors.groupingBy( s -> s.charAt(0) , //Groups by element initials, same in a group // counting() //Add this line of code to achieve grouping statistics);//The elements in the final groupingByList: {G=[Giraffe], L=[Lion, Lemur, Lion], M=[Monkey]}//If counting() is added, the result is: {G=1, L=3, M=1}

Here's a description of the process: groupingBy The first argument is a grouping condition, and the second argument is a child collector.

boolean containsTwo = IntStream.of(1, 2, 3).anyMatch(i -> i == 2);//determine whether the pipeline contains 2, the result is: truelong nrOfAnimals = Stream.of( "Monkey", "Lion", "Giraffe", "Lemur").count();//Total results of elemental data in pipeline nrOfAnimals: 4int sum = IntStream.of(1, 2, 3).sum();//Total results of elemental data in pipeline sum: 6OptionalDouble average = IntStream.of(1, 2, 3).average();//Average values of elemental data in pipeline average: OptionalDouble[2.0]int max = IntStream.of(1, 2, 3).max().orElse(0);//Maximum value of element data in pipeline max: 3IntSummaryStatistics = IntStream.of(1, 2, 3).summaryStatistics();//Overall statistics: IntSummaryStatistics{count=3, sum=6, min=1, average= 2.00000, max=3} At this point, the study of "java Stream API terminal operation example analysis" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

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