Foreword:
The stream() method has been around since Java 8. It is a product based on Lamada expressions. You can also simply view the stram stream as a foreach. More convenient for manipulating arrays or collections. And more secure. Because it is equivalent to doing a layer of SQL operations after fetching our data source, but it does not change the data source, but creates a new container to store the operated data.
Environment construction:
In order to be more in line with the business. We create an entity.
package org.java.demo;
import java.io.Serializable;
public class User implements Serializable {
//用户ID
private Long id;
//用户姓名
private String name;
//用户年龄
private Integer age;
//用户邮箱
private String email;
//↓get set 无参、有参构造器
//.....
}
public static void main(String[] args) {
User one = new User(1L,"one",12,"[email protected]");
User two = new User(2L,"two",17,"[email protected]");
User three = new User(3L,"three",25,"[email protected]");
User four = new User(4L,"four",43,"[email protected]");
List<User> list = new ArrayList<>();
list.add(one);
list.add(two);
list.add(three);
list.add(four);
}
Business practice
1. Take out an attribute of the collection object and save it in the new List collection.
list.stream().map(User::getName).collect(Collectors.toList());
2. Take out two attributes in the object and become a map collection in the form of key-value.
Note that the key value is the only attribute in the data source.
//id为key,name为value
list.stream().collect(Collectors.toMap(User::getId, User::getName));
//id为key,User对象为value 业务中比较常见。一般避免双重for循环时使用
list.stream().collect(Collectors.toMap(User::getId, User -> User));
3. Take out a certain value type attribute of the collection object and add it
list.stream().mapToInt(User::getAge).sum();
4. Take out a certain attribute in the collection object and remove it to form a new collection.
list.stream().map(User::getEmail).distinct().collect(Collectors.toList());
5. Take out an attribute in the collection object for string splicing
// 使用流 取属性 操作 工具类的拼接方法 拼接符
list.stream().map(User::getName).collect(Collectors.joining("-"));
//输出:one-two-three-four
6. Determine whether an attribute in the collection object meets the requirements
//判断所有属性是否满足要求,全部满足返回true
list.stream().allMatch(k -> k.getAge() > 18);
//输出:flase
//判断所有属性中只要有满足要求的便会返回true
list.stream().anyMatch(k -> k.getAge() > 18);
//输出:true
7. Filter a certain attribute value in the combined object
//过滤结合对象中,年龄大于20的封装成新集合
// 流 Lamda 判断 组装成新集合
list.stream().filter(k -> k.getAge() > 20).collect(Collectors.toList());
Summarize:
These are a few of the more commonly used methods in my work. There are still many methods that need to be supplemented.