** Java 8 是 Java 编程语言的一个重要版本,它引入了许多新特性和改进,使得 Java 开发变得更加高效和现代。**
下面我们就来使用Java8 快速实现List转map 、分组、过滤等操作。
定义1个用户对象
java
public class User {
private Integer id;
private String name;
private Integer age;
private String phone;
public User(Integer id, String name, Integer age, String phone) {
this.id = id;
this.name = name;
this.age = age;
this.phone = phone;
}
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;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
添加测试数据:
java
List<User> userList = new ArrayList<>();
User user1 = new User(1, "张三", 18, "12345678901");
User user2 = new User(2, "李四", 18, "12345678901");
User user3 = new User(3, "王五", 18, "12345678901");
User user4 = new User(4, "李白", 18, "12345678901");
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
1、分组
List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起:
java
Map<Integer, List<User>> groupBy = userList.stream().collect(Collectors.groupingBy(User::getId));
结果:
groupBy:{1=[User{id=1, name='张三', age=18, phone='12345678901'}], 2=[User{id=2, name='李四', age=18, phone='12345678901'}], 3=[User{id=3, name='王五', age=18, phone='12345678901'}], 4=[User{id=4, name='李白', age=18, phone='12345678901'}]}
2、List转Map
java
Map<Integer, User> UserMap = userList.stream().collect(Collectors.toMap(User::getId, a -> a,(k1,k2)->k1));
结果:
userMap:{1=User{id=1, name='张三', age=18, phone='12345678901'}, 2=User{id=2, name='李四', age=18, phone='12345678901'}, 3=User{id=3, name='王五', age=18, phone='12345678901'}, 4=User{id=4, name='李白', age=18, phone='12345678901'}}
3、过滤Filter
java
List<User> filterList = userList.stream().filter(a -> a.getName().equals("张三")).collect(Collectors.toList());
结果:
filterList:[User{id=1, name='张三', age=18, phone='12345678901'}]
4、求和
java
Integer total= userList.stream().map(User::getAge).reduce(0, Integer::sum);
结果:
total:72
5、查找流中最大 最小值
java
Optional<Dish> maxDish = Dish.menu.stream().
collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)));
maxDish.ifPresent(System.out::println);
Optional<Dish> minDish = Dish.menu.stream().
collect(Collectors.minBy(Comparator.comparing(Dish::getCalories)));
minDish.ifPresent(System.out::println);
6、去重
java
List<Integer> unique = userList.stream().map(User::getAge).distinct().collect(Collectors.toList());
结果:
unique:[18]