如何在java中遍历多个对象列表并获得对象摘要?

myzjeezk  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(341)

假设我有一节课,如下所示。

public class User {
    private String userType;
    private int numOfUsers;
}

并且有多个由用户类型的对象组成的列表。

List<User> list1 = < (userType:clerk, numofUsers:3 ), (userType:painter, numofUsers:4 ), (userType:engineer, numofUsers:10 ) >

List<User> list2 = < (userType:clerk, numofUsers:3 ),(userType:electrician, numofUsers:14 ), (userType:welder, numofUsers:5 ), (userType:engineer, numofUsers:10) >

List<User> list3 = < (userType:carpenter, numofUsers:4 ),(userType:welder, numofUsers:10 ) >

我需要创建一个用户列表,它给出每种类型的用户对象的总和,如下所示。

List<User> userCount  = < (userType:clerk, numofUsers:6 ), (userType:painter, numofUsers:4 ), (userType:engineer, numofUsers:20 ),(userType:electrician, numofUsers:14 ), (userType:carpenter, numofUsers:4 ) ,(userType:welder, numofUsers:15 ) >

我如何在java中做到这一点?

ryoqjall

ryoqjall1#

您可以使用java流api。使用 Collectors.toMap 合并 NumOfUsers 对于同一类型。然后获取arraylist中的值。

List<User> result = new ArrayList<>(
       Stream.of(list1, list2, list3)  // Stream of List of List
        .flatMap(Collection::stream)   // Flatten into a single list
        .collect(Collectors.toMap(User::getUserType, i -> i,   //Map by UserType and  merge user having same type
                 (a,b) -> new User(a.getUserType(), a.getNumOfUsers() + b.getNumOfUsers())))
        .values());   // Take only values of the map
esbemjvw

esbemjvw2#

您是否希望使用:

List<User> result = Stream.of(list1, list2, list3)
        .flatMap(Collection::stream)
        .collect(Collectors.groupingBy(User::getUserType, Collectors.summingInt(User::getNumOfUsers)))
        .entrySet().stream()
        .map(e -> new User(e.getKey(), e.getValue()))
        .collect(Collectors.toList());

相关问题