Java8操作List<Object>小结
在项目开发中,经常遇到对List<Object>的操作,比如取最值、排序、汇总求和、转Map等等。今天在此做个小结,希望和大家一起学习,如有遗漏的地方还请大家指正!
一、准备一个测试类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<User> 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<Integer> ids = userList.stream().map(User::getId).collect(Collectors.toList());
System.out.println("获取id集合:"+ids);
//获取key为id,value为对象的Map
Map<Integer, User> 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<User> filterUser = userList.stream().filter(u -> u.getAge() > 10).collect(Collectors.toList());
System.out.println("获取age大于10的user:"+filterUser);
//按年龄正序排序
List<User> ascList = userList.stream().sorted(Comparator.comparingInt(User::getAge)).collect(Collectors.toList());
System.out.println("按年龄排序:正序:"+ascList);
//按年龄逆序排序
List<User> 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);
}
}
四、结果输出:
