在项目开发中,经常遇到对List
一、准备一个测试类User:
public class User {
private Integer id;
private String name;
private Integer age;
public User(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + ''' +
", age=" + age +
'}';
}
}
二、编码:
①获取id集合
userList.stream().map(User::getId).collect(Collectors.toList());
②获取key为id,value为对象的Map
userList.stream().collect(Collectors.toMap(User::getId, User -> User));
③获取age最大的user
userList.stream().max(Comparator.comparingInt(User::getAge)).get();
④获取age大于10的user
userList.stream().filter(u -> u.getAge() > 10).collect(Collectors.toList());
⑤按年龄正序排序
userList.stream().sorted(Comparator.comparingInt(User::getAge)).collect(Collectors.toList());
⑥按年龄逆序排序
userList.stream().sorted(Comparator.comparingInt(User::getAge).reversed()).collect(Collectors.toList());
⑦按年龄求和
userList.stream().mapToInt(User::getAge).sum();
三、编写测试类:
public class TestUser {
private static List userList = new ArrayList<>();
static{
userList.add(new User(1,"张三",10));
userList.add(new User(2,"李四",15));
userList.add(new User(3,"王五",20));
}
public static void main(String[] args) {
System.out.println(userList);
//获取id集合
List ids = userList.stream().map(User::getId).collect(Collectors.toList());
System.out.println("获取id集合:"+ids);
//获取key为id,value为对象的Map
Map userMap = userList.stream().collect(Collectors.toMap(User::getId, User -> User));
System.out.println("获取key为id,value为对象的Map:"+userMap);
//获取age最大的user
User user = userList.stream().max(Comparator.comparingInt(User::getAge)).get();
System.out.println("获取age最大的user:"+user);
//获取age大于10的user
List filterUser = userList.stream().filter(u -> u.getAge() > 10).collect(Collectors.toList());
System.out.println("获取age大于10的user:"+filterUser);
//按年龄正序排序
List ascList = userList.stream().sorted(Comparator.comparingInt(User::getAge)).collect(Collectors.toList());
System.out.println("按年龄排序:正序:"+ascList);
//按年龄逆序排序
List descList = userList.stream().sorted(Comparator.comparingInt(User::getAge).reversed()).collect(Collectors.toList());
System.out.println("按年龄逆序排序:"+descList);
//按年龄求和
int sumAge = userList.stream().mapToInt(User::getAge).sum();
System.out.println("按年龄求和:"+sumAge);
}
}
四、结果输出:



