• 周六. 10 月 12th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

【java_ Deep foundation] grouping operation of java8 stream | collections API

King Wang

1 月 3, 2022

Java8 Stream | Collections API Of Grouping operation

Initial data

 // Initial data 
List<User> userList = Arrays.asList(
new User("zhangsan", 10),
new User("zhangsan", 12),
new User("lisi", 10),
new User("wangwu", 15),
new User("zhaoliu", 0)
);

1. Common group Collectors.groupingBy

 // Use grouping grouping , according to Name grouping 
Map<String, List<User>> map = userList.stream().collect(Collectors.groupingBy(user -> user.getName()));
log.info(" Use grouping grouping : \n {} \n", JSON.toJSON(map));

2. Common group Collectors.groupingBy + Collectors.mapping

mapping Used to return a new object , It’s not just grouping , Or use the grouped intra group elements to return

 /**
* test steam Grouping function , Filter
* @param args
*/
public static void main(String[] args) {

// Use grouping and mapping grouping 
Map<String, List<UserEnhance>> map1 = userList.stream()
.collect(
Collectors.groupingBy(
user -> user.getName(),
Collectors.mapping(p -> new UserEnhance(p.getName(), p.getAge()) ,Collectors.toList())
)
);
log.info(" Use grouping and mapping grouping : \n {} \n", JSON.toJSON(map1));
// Use grouping and mapping grouping , The content of the group is specific to an attribute 
Map<String, List<Integer>> map2 = userList.stream()
.collect(
Collectors.groupingBy(
user -> user.getName(),
Collectors.mapping(user -> user.getAge(),Collectors.toList())
)
);
log.info(" Use grouping and mapping grouping , The content of the group is specific to an attribute , \n {} \n", JSON.toJSON(map2));
// Grouping after de duplication 
Map<String, User> map3 = userList.stream()
.filter(p -> Objects.nonNull(p.getAge()) && p.getAge() != 0)
.collect(
Collectors.toMap(
user -> user.getName(),
user -> new User(user.getName(), user.getAge()),
(v1, v2) -> v1.getAge() > v2.getAge() ? v1 : v2)
);
log.info(" Grouping after de duplication : \n {} \n", JSON.toJSON(map3));
// Use map() extract 
List<String> userNameList = userList.stream().map(p -> p.getName()).collect(Collectors.toList());
// Use mapping After extraction, put in New list
List<String> userNameListWithMapper = new ArrayList<>();
// in addition ,map(...) Rules can be passed in as parameters 
Function<User,String> mapper= p -> p.getName();
userNameListWithMapper = userList.stream().map(mapper).collect(Collectors.toList());
log.info(" Ordinary map extract : \n {} \n", JSON.toJSON(userNameList));
log.info(" Use external mapper: \n {} \n", JSON.toJSON(userNameListWithMapper));
}

发表回复