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 flow example of Java

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

Share

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

This article focuses on "Stream stream example analysis of Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "Java Stream stream example analysis" it!

Stream flow

The last article talked about a new feature of Java 8: Lambda expressions, which can save a lot of code and look much cleaner if they are used skillfully in business. So this article will introduce another new feature: Stream stream, don't get it wrong! Not a video game player, Steamboy!

1. What is a Stream stream:

Stream is a new concept proposed by Java 8, which is not a Stream stream of input and output (which has nothing to do with IO stream), but a tool that uses functional programming to operate on collection classes. In short, it is the operation of dealing with collection data in an internal iteration, which can give more control to the collection class. The function of Stream is similar to that of Iterator, except that Iterator handles aggregate data in the form of external iterations.

Of course, Stream has its own features:

1. Is not a data structure, does not store data, but defines a set of operations on the original dataset

two。 These operations are lazy, that is, a series of operations are performed on an element in the stream whenever it is accessed.

3. Because the data is not saved, each Stream stream can only be used once.

Implementation diagram of the Stream flow:

2. Create a stream:

If you want to manipulate a collection with a Stream stream, you need to convert the array or collection into a Stream stream before you can operate.

Official documentation of Stream:

Https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/stream/Stream.html

Let's take a look at four ways:

1.filter: conditional filtering through lambda expressions

2.limit: intercepts a stream and intercepts a stream

3.skip: skipping flow

4.distinct: remove repetition

Create a Stream:

Public class Test {public static void main (String [] args) {String [] arr = {"East", "South", "West", "North"}; / / convert the array to Stream Stream stream = Arrays.stream (arr); stream = Stream.of (arr); stream = Stream.of ("East", "South", "West", "North") / / convert the list collection to stream List list = Arrays.asList ("aa", "cc", "bb", "aa", "dd"); stream = list.stream (); / / sort, deduplicate, and traverse list.stream (). Sorted (). Distinct (). ForEach (System.out::println) / / after manipulating the collection with Stream stream, you can convert it to a new collection List newList = list.stream (). Sorted (). Distinct (). Collect (Collectors.toList ()); System.out.println (newList.toString ());}}

Output:

/ / the result of traversing and deduplicating:

Aa

Bb

Cc

Dd

/ / after manipulating the collection with Stream stream, you can convert it to a new collection.

[aa, bb, cc, dd]

Operation of four methods: Person class:

There is a lot of code in this class, so don't write the get/set method into it, don't forget when you use it!

Public class Person {private String name; private Integer age; private String country; private char sex @ Override public String toString () {return "Information Table: {" + "name='" + name +'\'+ ", age=" + age + ", country='" + country +'\'+ ", sex=" + sex +'}' } / / the get/set code saved here / / rewrite toString () and equals and hashcode methods @ Override public boolean equals (Object o) {if (this = = o) return true; if (o = = null | | getClass ()! = o.getClass ()) return false; Person person = (Person) o If (country! = null) {if (this.country.equals (person.country)) {return true;} else {return false;}} return false;} @ Override public int hashCode () {return Objects.hash (country);}}

Test class:

Combined with lambda expressions to write

Public class Test {public static void main (String [] args) {List perosnList = new ArrayList (); perosnList.add (new Person ("Wang Yi", 30, "China",'M')); perosnList.add ("Zhang San", 19, "USA",'F')); perosnList.add ("Li Si", 29, "Japan",'F')) PerosnList.add ("Xiaomei", 74, "UK",'M'); perosnList.add ("Bear II", 15, "Italy",'F'); perosnList.add ("Xiong Da", 66, "Korea",'F')) / / return the collection of students older than 20 years old System.out.println ("return the collection of students over 20 years old"); perosnList.stream () .filter (p-> p.getAge () > 20) .forEach (System.out::println); / / return the collection of students older than 50 years old System.out.println ("return collection of students older than 50 years old") List list = perosnList.stream () .filter (p-> p.getAge () > 50) .students (Collectors.toList ()); System.out.println (list); / / return to Chinese students over 20 years old System.out.println ("return to Chinese people over 20 years old") PerosnList.stream () .filter (p-> p.getAge () > 20) .filter (p-> p.getCountry (). Equals ("Korea")) .forEach (System.out::println); / / Chinese sex M System.out.println over 20 ("return age > 20 Chinese sex M") PerosnList.stream () .filter (p-> p.getAge () > 20 & & p.getCountry (). Equals ("China") & & p.getSex () = ='M') .forEach (System.out::println);}}

Look at the results:

Returns a collection of students over the age of 20

Information sheet: {name=' Wang', age=30, country=' China', sex=M}

Information table: {name=' Li Si', age=29, country=' Japan', sex=F}

Information sheet: {name=' Xiaomei', age=74, country=' UK', sex=M}

Information table: {name=' Xiong Da', age=66, country=' Korea', sex=F}

Returns a collection older than 50 years old

[information sheet: {name=' Xiaomei', age=74, country=' UK', sex=M}, Information Table: {name=' Xiong Da', age=66, country=' Korea', sex=F}]

Return to Chinese people over the age of 20

Information table: {name=' Xiong Da', age=66, country=' Korea', sex=F}

Return to the Chinese sex M over 20 years old

Information sheet: {name=' Wang', age=30, country=' China', sex=M}

Summary:

Using Stream streams, you can easily manipulate arrays or collections, and you can combine Lambda expressions to make an expression neat and clear, but since it is a new feature of Java exit, it must be useful.

3. The function of Stream's map mapping stream public class Test {public static void main (String [] args) {/ / map is to iterate over each list element, and then perform the corresponding operation List list1 = Arrays.asList ("a", "bb", "ccc", "dddd") through the functions in map. / / get the length of each collection element through map and return Stream stream = list1.stream () .map (p-> p.length ()); stream.forEach (System.out::println); System.out.println ("-"); List userList = new ArrayList (); userList.add ("Jay Chou") UserList.add ("Nicholas. Zhao Si "; userList.add (" Newton. Pakistan "); userList.add (" Zhao Shaohua. Smecta "); List uList = userList.stream (). Map (p-> p.substring (p.indexOf (". ") + 1, p.length ()). Collectors.toList (); System.out.println (uList.toString ());}}

Output:

one

two

three

four

-

[tom, Zhao Si, Pakistan, Smecta]

4. Stream search and match

There is also an anyMatch (Predicate predicate) method in Stream:

Returns whether any element in this stream matches the provided word

Demo:

Public class Test {public static void main (String [] args) {List list = Arrays.asList ("Jay Chou", "Wang Leehom", "Stefanie Sun", "Lin Junjie"); boolean flag1 = list.stream (). AnyMatch (ele- > ele.contains ("Yan"); System.out.println ("students whose names include Yan:" + flag1) / / judge the beginning: boolean flag2 = list.stream (). AnyMatch (ele- > ele.startsWith ("Wang"); System.out.println ("is there any classmate whose name begins with Wang:" + flag2); / / judge the end: boolean flag3 = list.stream (). AnyMatch (ele- > ele.endsWith ("Jie"); System.out.println ("No classmate whose name ends with Jay:" + flag3) / / anyMatch matches all, to meet the conditions boolean flag4 = list.stream (). AnyMatch (ele- > ele.length () > 2); System.out.println ("are all students' names more than two words" + flag4); boolean flag5 = list.stream (). AnyMatch (ele- > ele.startsWith ("Wang"); System.out.println ("do all students have Wang's names?" + flag5); / / noneMatch boolean flag6 = list.stream (). NoneMatch (ele- > ele.contains ("Yan")); System.out.println ("does not include the word 'Yan' in the collection" + flag5);}}

Output:

Is there a classmate whose name includes Yan: true

Is there a classmate whose name begins with Wang: true

Is there a classmate whose name ends with Jay: true

Are all the students' names more than two words, true?

Do all the students have Wang in their names? True

Does not include the word "Yan" in the collection, true?

Using the method in anyMatch (), you can easily match the information of this stream.

At this point, I believe you have a deeper understanding of "Java's Stream stream instance analysis". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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: 232

*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