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! !
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:
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.
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]
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!