0

Suppose I have a class as follows.

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

And there are more than one list which consists objects of User type.

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 ) >

I need to create single list of users which gives the summation of every types of user objects as follows.

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 ) >

How can i do that in Java?

1
  • Can you show us what you have tried so far? Commented Aug 19, 2020 at 7:33

2 Answers 2

3

Are you looking to use :

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());
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Java Stream API. Use Collectors.toMap and merge NumOfUsers for same type. Then get the values in 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

1 Comment

Thank you @User - Upvote don't say Thanks. This answer also works for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.