java8--List转为Map、分组、过滤、求和等操作
2018-06-13 本文已影响0人
YNZXGWZM
public static void main(String[] args) {
List<User> userList = new ArrayList<User>();
User user0 = new User("付萌朝1", "男1", 20);
User user1 = new User("付萌朝1", "男", 20);
User user2 = new User("付萌朝2", "男", 21);
User user3 = new User("付萌朝3", "男", 22);
User user4 = new User("付萌朝4", "男", 23);
User user5 = new User("付萌朝5", "男", 24);
userList.add(user0);
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
userList.add(user5);
/**
* list 转map
* 注意:要是key重复的话 会报错Duplicate key ....
* key name 都是付萌朝1
* 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
* result
* 付萌朝4=23===男
付萌朝3=22===男
付萌朝2=21===男
付萌朝1=20===男1
付萌朝5=24===男
*/
Map<String,Object> compMap= userList.stream().collect(Collectors.toMap(User::getName, a -> a.getAge() + "===" + a.getSex(), (k1, k2) -> k1));
for(Object obj : compMap.keySet()) {
String key = (String) obj;//取到每一个key值
String value = (String) compMap.get(key);
System.out.println(key + "=" + value);
}
/**
* list中以某个属性分组,比如用name分组
*/
Map<String,List<User>> map= userList.stream().collect(Collectors.groupingBy(User::getName));
System.out.println(map);
}