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

What are the common methods of Stream in Java8

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

In this article Xiaobian for you to introduce in detail "what are the common methods of Stream in Java8", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "what are the common methods of Stream in Java8" can help you solve your doubts.

Brief introduction

Java8 has been out for a long time, but it is still necessary to know about interface default methods, lambda expressions, functional interfaces, Date API and other features. For example, collections are often used in projects, traversing collections can try lambda expressions, and often filter and sort collections, so Stream comes in handy. I'm used to it. I have to say it's really easy to use.

As a new feature of java8, Stream, based on lambda expression, enhances the function of collection objects. It focuses on a variety of efficient and convenient aggregation operations or mass data operations on collection objects, which improves programming efficiency and code readability.

The principle of Stream: the element to be processed is treated as a stream, which is transmitted in the pipeline and can be processed on the nodes of the pipeline, including filtering, deduplication, sorting, aggregation, and so on. The element flow is processed by the intermediate operation in the pipeline, and finally the result of the previous processing is obtained by the final operation.

Collections have two ways to generate flows:

Stream () − creates a serial flow for the collection

ParallelStream ()-creates a parallel flow for the collection

The above figure is the class structure diagram of the Stream class, which contains most of the intermediate and termination operations.

The main intermediate operations are as follows (this type of method returns Stream): map (mapToInt, flatMap, etc.), filter, distinct, sorted, peek, limit, skip, parallel, sequential, unordered

There are mainly the following methods to terminate the operation: forEach, forEachOrdered, toArray, reduce, collect, min, max, count, anyMatch, allMatch, noneMatch, findFirst, findAny, iterator

Give examples to illustrate

First of all, in order to illustrate the operation of Stream on the object collection, create a new Student class (student class) and override the equals () and hashCode () methods

Public class Student {private Long id; private String name; private int age; private String address; public Student () {} public Student (Long id, String name, int age, String address) {this.id = id; this.name = name; this.age = age; this.address = address } @ Override public String toString () {return "Student {" + "id=" + id + ", name='" + name +'\'+ ", age=" + age + ", address='" + address +'\'+'}' } @ Override public boolean equals (Object o) {if (this = = o) return true; if (o = = null | | getClass ()! = o.getClass ()) return false; Student student = (Student) o Return age = = student.age & & Objects.equals (id, student.id) & & Objects.equals (name, student.name) & & Objects.equals (address, student.address);} @ Override public int hashCode () {return Objects.hash (id, name, age, address);} public Long getId () {return id } public void setId (Long id) {this.id = id;} public String getName () {return name;} public void setName (String name) {this.name = name;} public int getAge () {return age;} public void setAge (int age) {this.age = age } public String getAddress () {return address;} public void setAddress (String address) {this.address = address;}}

Filter (filter)

Public static void main (String [] args) {Student S1 = new Student (1L, "Xiao Zhan", 15, "Zhejiang"); Student S2 = new Student (2L, "Wang Yibo", 15, "Hubei"); Student S3 = new Student (3L, "Yang Zi", 17, "Beijing"); Student S4 = new Student (4L, "Li Xian", 17, "Zhejiang") List students = new ArrayList (); students.add (S1); students.add (S2); students.add (S3); students.add (S4); List streamStudents = testFilter (students); streamStudents.forEach (System.out::println) } / * screening of collections * @ param students * @ return * / private static List testFilter (List students) {/ / screening students over 15 years old / / return students.stream () .filter (s-> s.getAge () > 15) .screening (Collectors.toList ()) / / screen students living in Zhejiang Province return students.stream (). Filter (s-> "Zhejiang" .equals (s.getAddress () .students (Collectors.toList ());}

Running result:

Here we created four students, after filter screening, screened out the address is a collection of students from Zhejiang.

Map (conversion)

Public static void main (String [] args) {Student S1 = new Student (1L, "Xiao Zhan", 15, "Zhejiang"); Student S2 = new Student (2L, "Wang Yibo", 15, "Hubei"); Student S3 = new Student (3L, "Yang Zi", 17, "Beijing"); Student S4 = new Student (4L, "Li Xian", 17, "Zhejiang") List students = new ArrayList (); students.add (S1); students.add (S2); students.add (S3); students.add (S4); testMap (students) } / * set conversion * @ param students * @ return * / private static void testMap (List students) {/ / add some information in front of the address to get only the address output List addresses = students.stream () .map (s-> "residential address:" + s.getAddress ()) .address (Collectors.toList ()); addresses.forEach (a-> System.out.println (a)) }

Running result

Map is to transform the corresponding elements according to the given method.

Distinct (de-weight)

Public static void main (String [] args) {testDistinct1 ();} / * set deduplication (basic type) * / private static void testDistinct1 () {/ / simple string deduplication List list = Arrays.asList ("111,222,333,111,222,222"); list.stream () .distinct () .forEach (System.out::println);}

Running result:

Public static void main (String [] args) {testDistinct2 ();} / * collection to deduplicate (reference object) * / private static void testDistinct2 () {/ / reference object to implement hashCode and equal methods, otherwise deduplicated invalid Student S1 = new Student (1L, "Xiao Zhan", 15, "Zhejiang") Student S2 = new Student (2L, "Wang Yibo", 15, "Hubei"); Student S3 = new Student (3L, "Yang Zi", 17, "Beijing"); Student S4 = new Student (4L, "Li Xian", 17, "Zhejiang"); Student S5 = new Student (1L, "Xiao Zhan", 15, "Zhejiang"); List students = new ArrayList (); students.add (S1) Students.add (S2); students.add (S3); students.add (S4); students.add (S5); students.stream (). Distinct (). ForEach (System.out::println);}

Running result:

It can be seen that two repeated "Xiao Zhan" students have removed the weight, not only because of the use of the distinct () method, but also because the Student object overrides the equals and hashCode () methods, otherwise deduplication is invalid.

Sorted (sort)

Public static void main (String [] args) {testSort1 ();} / * set sort (default sort) * / private static void testSort1 () {List list = Arrays.asList ("333,222,111"); list.stream () .sorted () .forEach (System.out::println);}

Running result:

Public static void main (String [] args) {testSort2 ();} / * set sort (specify collation) * / private static void testSort2 () {Student S1 = new Student (1L, "Xiao Zhan", 15, "Zhejiang"); Student S2 = new Student (2L, "Wang Yibo", 15, "Hubei"); Student S3 = new Student (3L, "Yang Zi", 17, "Beijing") Student S4 = new Student (4L, "Li Xian", 17, "Zhejiang"); List students = new ArrayList (); students.add (S1); students.add (S2); students.add (S3); students.add (S4) Students.stream () .sorted ((stu1,stu2)-> Long.compare (stu2.getId (), stu1.getId () .sorted ((stu1,stu2)-> Integer.compare (stu2.getAge (), stu1.getAge () .forEach (System.out::println);}

Running result:

The sorting rules specified above are sorted in descending order according to the students'id, and then by age.

Limit (limit the number of returns)

Public static void main (String [] args) {testLimit ();} / * collection limit, returns the first few elements * / private static void testLimit () {List list = Arrays.asList ("333,222,111"); list.stream () .limit (2) .forEach (System.out::println);}

Running result:

Skip (delete element)

Public static void main (String [] args) {testSkip ();} / * set skip, delete the first n elements * / private static void testSkip () {List list = Arrays.asList ("333,222,111"); list.stream () .skip (2) .forEach (System.out::println);}

Running result:

Reduce (aggregation)

Public static void main (String [] args) {testReduce ();} / * set reduce, aggregating each element in the collection into a single piece of data * / private static void testReduce () {List list = Arrays.asList ("Huan", "Ying", "you"); String appendStr = list.stream (). Reduce ("Beijing", (aMagneb)-> ahumb) System.out.println (appendStr);}

Running result:

Min (minimum value)

Public static void main (String [] args) {testMin ();} / * find the minimum value of the elements in the set * / private static void testMin () {Student S1 = new Student (1L, "Xiao Zhan", 14, "Zhejiang"); Student S2 = new Student (2L, "Wang Yibo", 15, "Hubei") Student S3 = new Student (3L, "Yang Zi", 17, "Beijing"); Student S4 = new Student (4L, "Li Xian", 17, "Zhejiang"); List students = new ArrayList (); students.add (S1); students.add (S2); students.add (S2); students.add (S4) Student minS = students.stream () .min ((stu1,stu2)-> Integer.compare (stu1.getAge (), stu2.getAge ()) .get (); System.out.println (minS.toString ());}

Running result:

The above is to find the youngest of all the students, max in the same way, to find the maximum.

AnyMatch/allMatch/noneMatch (match)

Public static void main (String [] args) {testMatch ();} private static void testMatch () {Student S1 = new Student (1L, "Xiao Zhan", 15, "Zhejiang"); Student S2 = new Student (2L, "Wang Yibo", 15, "Hubei"); Student S3 = new Student (3L, "Yang Zi", 17, "Beijing") Student S4 = new Student (4L, "Li Xian", 17, "Zhejiang"); List students = new ArrayList (); students.add (S1); students.add (S2); students.add (S3); students.add (S4); Boolean anyMatch = students.stream (). AnyMatch (s-> Hubei .equals (s.getAddress () If (anyMatch) {System.out.println ("Hubei people");} Boolean allMatch = students.stream (). AllMatch (s-> s.getAge () > = 15); if (allMatch) {System.out.println ("all students have reached the age of 15") } Boolean noneMatch = students.stream (). NoneMatch (s-> "Yang Yang" .equals (s.getName ()); if (noneMatch) {System.out.println ("no classmate named Yang Yang");}}

Running result:

Any element in anyMatch:Stream matches the passed predicate and returns true

All elements in allMatch:Stream match the passed predicate and return true

None of the elements in noneMatch:Stream match the passed predicate, and true is returned.

After reading this, the article "what are the common methods of Stream in Java8" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, 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