Analyze Stream flow instances in Java
Stream flow
The previous article talked about a new feature of Java 8: Lambda expression. If you can use it skillfully in business, you can save money. There is a lot of code and it looks a lot neater. Then this article will introduce another new feature: Stream stream, don’t read it wrong! ! ! Not for playing games steam! !
1. What is a Stream:
Stream is a new concept proposed by Java 8. It is not an input and output Stream (it is not the same as the IO stream. Any relationship ha), but a tool that uses functional programming to operate on collection classes. In short, it is an operation of processing collection data in an internal iteration method. Internal iteration can give more control to the collection class. The functions of Stream and Iterator are similar, except that Iterator is an operation that processes collection data in the form of external iteration.
Of course Stream also has its own characteristics:
1. It is not a data structure and does not store data. It just defines a set of operations on the original data set
2. These operations are lazy, that is, whenever an element in the stream is accessed, this series of operations will be performed on this element
3. Because the data is not saved, each Stream Streams can only be used once.
Implementation diagram of Stream stream:
2. Create stream:
If you want to use Stream stream to To operate a collection, you need to convert the array or collection into a Stream first before you can operate
Official document of Stream:
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/stream/Stream.html
Let’s look at four first Method:
1.filter: Implement conditional filtering through lambda expressions
2.limit: Intercept the stream, intercept a section of the stream
3.skip: Skip Overflow
4.distinct: Remove duplicates
Create Stream:
public class Test { public static void main(String[] args) { String [] arr = {"东","南","西","北"}; //将数组转换成Stream Stream<String> stream = Arrays.stream(arr); stream = Stream.of(arr); stream = Stream.of("东","南","西","北"); //将list集合转换成stream List<String> list = Arrays.asList("aa","cc","bb","aa","dd"); stream = list.stream(); //排序、去重、遍历 list.stream().sorted().distinct().forEach(System.out::println); //用过Stream流操作完集合后还可以再转换成一个新的集合 List<String> newList = list.stream().sorted().distinct().collect(Collectors.toList()); System.out.println(newList.toString()); } }
Output:
//The result after traversing and deduplicating:
aa
bb
cc
dd
//After using the Stream stream to operate the collection, it can be converted into a new one Collection
[aa, bb, cc, dd]
Operations of four methods: Person class:
Code comparison of this class Many, so don’t write the get/set method in it. Don’t forget it when you use it! !
public class Person { private String name; private Integer age; private String country; private char sex; @Override public String toString() { return "信息表:{" + "name='" + name + '\'' + ", age=" + age + ", country='" + country + '\'' + ", sex=" + sex + '}'; } //这里节省的get/set代码 //重写toString() 和 equals 和 hashcode 方法 @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 expression to write
public class Test { public static void main(String[] args) { List<Person> perosnList = new ArrayList<>(); perosnList.add(new Person("王一", 30, "中国", 'M')); perosnList.add(new Person("张三", 19, "美国", 'F')); perosnList.add(new Person("李四", 29, "日本", 'F')); perosnList.add(new Person("小美", 74, "英国", 'M')); perosnList.add(new Person("熊二", 15, "意大利", 'F')); perosnList.add(new Person("熊大", 66, "韩国", 'F')); //返回年龄大于20岁的学生集合 System.out.println("返回年龄大于20岁的学生集合"); perosnList.stream().filter(p -> p.getAge() > 20).forEach(System.out::println); //返回年龄大于50岁的学生集合 System.out.println("返回年龄大于50岁的集合"); List<Person> list = perosnList.stream().filter(p -> p.getAge() > 50).collect(Collectors.toList()); System.out.println(list); //返回年龄大于20岁的中国学生 System.out.println("返回年龄大于20岁的中国人"); perosnList.stream().filter(p -> p.getAge() > 20).filter(p -> p.getCountry().equals("韩国")).forEach(System.out::println); //年龄大于20 中国 性别M System.out.println("返回年龄大于20 中国 性别M"); perosnList.stream().filter(p -> p.getAge() > 20 && p.getCountry().equals("中国") && p.getSex() == 'M').forEach(System.out::println); } }
Look at the result:
Return the collection of students older than 20 years old
Information table: {name='Wang Yi', age=30, country='China', sex=M}
Information table: {name='李思', age=29, country='Japan', sex=F}
Information table: {name='Xiaomei', age=74, country='UK', sex=M}
Information table: {name='Xiong Da', age=66, country='Korea', sex=F}
Return the collection of people older than 50 years old
[Information table: {name='小Beauty', age=74, country='UK', sex=M}, information table: {name='Xiong Da', age=66, country='South Korea', sex=F}]
Return age greater than 20-year-old Chinese
Information table: {name='Xiong Da', age=66, country='South Korea', sex=F}
Return age greater than 20 China GenderM
Information table: { name='Wang Yi', age=30, country='China', sex=M}
Summary:
Using Stream can be easily operated Arrays or collections can be combined with Lambda expressions to make an expression neat and clear. In fact, since it is a new feature exited by Java, it must be useful.
3. Stream map mapping stream
public class Test { public static void main(String[] args) { //map的作用是迭代取到每个list元素,再通过map里面的函数进行相应的操作 List<String> list1 = Arrays.asList("a","bb","ccc","dddd"); //通过map取到每个集合元素的长度并返回 Stream<Integer> stream = list1.stream().map(p->p.length()); stream.forEach(System.out::println); System.out.println("----------------"); List<String> userList = new ArrayList<>(); userList.add("周杰伦.tom"); userList.add("尼古拉斯.赵四"); userList.add("牛顿.巴基斯"); userList.add("赵少华.思密达"); List<String> uList = userList.stream().map(p->p.substring(p.indexOf(".")+1, p.length())).collect(Collectors.toList()); System.out.println(uList.toString()); } }
Output:
1
2
3
4
----------------
[tom, Zhao Si, Bakis, Smecta]
4. Stream search and There is also a
anyMatch(Predicate predicate) method in the matching Stream:
Returns whether any element in this stream matches the provided word
Demo:
public class Test { public static void main(String[] args) { List<String> list = Arrays.asList("周杰伦","王力宏","孙燕姿","林俊杰"); boolean flag1 = list.stream().anyMatch(ele->ele.contains("燕")); System.out.println("有没有名字包含燕的同学:"+flag1); //判断开头: boolean flag2 = list.stream().anyMatch(ele->ele.startsWith("王")); System.out.println("有没有名字开头是王的同学:"+flag2); //判断结尾: boolean flag3 = list.stream().anyMatch(ele->ele.endsWith("杰")); System.out.println("有没有名字结尾是杰的同学:"+flag3); // anyMatch是匹配所有的,要满足条件 boolean flag4 = list.stream().anyMatch(ele->ele.length()>2); System.out.println("所有同学的名字都是两个字以上的吗"+flag4); boolean flag5 = list.stream().anyMatch(ele->ele.startsWith("王")); System.out.println("所有同学的名字都有王吗?"+flag5); //noneMatch boolean flag6 = list.stream().noneMatch(ele->ele.contains("燕")); System.out.println("集合中都没有包含'燕'这个字吗"+flag5); } }
Output:
Are there any students whose names contain Yan: true
Are there any students whose names start with Wang: true
Are there any students whose names end with Jie: true
Do all students’ names have more than two characters? true
All students’ names have Wang ? true
The collection does not contain the word 'Yan' true
Using the method in anyMatch() can easily match the information of this stream.
The above is the detailed content of Analyze Stream flow instances in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
