Home > database >  Java 8 grouping by using a count [closed]
Java 8 grouping by using a count [closed]

Time:09-29

I need to implement an function that return an Map<Integer, List<User>> but i need to group by count of products.I must to do this using an stream. The code:

public class User {
 private List<Product> products;
    public List<Product> getProducts() {
            
            return products;
        }
}



public Map<Integer, List<User>> groupByCountOfProducts(final List<User> users) {
        return users.stream()... some code
    }

I need to implement this method.I found that i can use grouping by but i do not know how to do this properly

Some input:

 final User user1 = new User(1L, "John", "Doe", 26, asList(Product.Carrot, Product.Onion));
   final User user2 = new User(1L, "John", "Doe", 26, asList(Product.Carrot, Product.Onion,Product.Beans));

final Map<Integer, List<User>> groupedMap =
                groupByCountOfPrivileges(asList(user1,user2));

CodePudding user response:

You can use groupingBy on the size of the products list of the User

public Map<Integer, List<User>> groupByCountOfProducts(final List<User> users) {
    return users.stream().collect(Collectors.groupingBy(user -> user.getProducts().size()));
}

You can also use streams on the products list of User as (but you have to change your return type to Map<Long, List<User>> instead of Map<Integer, List<User>>:

public static Map<Long, List<User>> groupByCountOfProducts(final List<User> users) {
    return users.stream().collect(Collectors.groupingBy(user -> user.getProducts().stream().count()));
}
  • Related