Java 8 使用计数分组

Java 8 grouping by using a count

我需要实现 return 和 Map<Integer, List<User>> 的功能 但我需要按 products.I 的计数进行分组,必须使用流来执行此操作。 代码:

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
    }

我需要实现这个 method.I 发现我可以使用分组依据,但我不知道如何正确地做到这一点

部分输入:

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

您可以在 User

的产品列表尺寸上使用 groupingBy
public Map<Integer, List<User>> groupByCountOfProducts(final List<User> users) {
    return users.stream().collect(Collectors.groupingBy(user -> user.getProducts().size()));
}

您还可以使用 Userproducts 列表中的流作为(但您必须将 return 类型更改为 Map<Long, List<User>> 而不是 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()));
}