使用Java 8流分组是通过字符串列表的列表吗?

时间:2018-06-19 16:35:32

标签: java collections java-8 java-stream

我有以下字符串列表

List<String> product_a= Arrays.asList("Product A", "Category A", "Price");
List<String> product_b= Arrays.asList("Product A", "Category A", "Price");
List<String> product_c= Arrays.asList("Product B", "Category B", "Price");
List<String> product_d = Arrays.asList("Product C", "Category C", "Price");

然后,我将它们放在另一个列表中

List<List<String>> products = new ArrayList<>();
products.add(product_a);
products.add(product_b);
products.add(product_c);
products.add(product_d);

使用Streams,Collectors.groupingBy,Collectors.counting,如何获得以下输出?有可能吗?

Product A - 2
Product B - 1
Product C - 1

预先,谢谢您的帮助。

1 个答案:

答案 0 :(得分:10)

您的意思是:

Map<String, Long> group = products.stream()
        .collect(Collectors.groupingBy(c -> c.get(0), Collectors.counting()));

group.entrySet().forEach(c -> System.out.println(c.getKey() + " - " + c.getValue()));

输出

Product A - 2
Product B - 1
Product C - 1

但是我想创建一个包含这三个信息product category price的类,而不是为每个项目使用列表。

class Product{
    private String productName;
    private String category;
    private BigDecimal price;

    //constructors getters setters
}

然后将您的产品填写到产品列表中,如下所示:

List<Product> products = new ArrayList<>();
products.add(new Product("Product A", "Category A", new BigDecimal("123")));
products.add(new Product("Product A", "Category A", new BigDecimal("456")));
products.add(new Product("Product B", "Category B", new BigDecimal("696")));
products.add(new Product("Product C", "Category C", new BigDecimal("66")));

那么您的分组可以是:

Map<String, Long> group = products.stream()
        .collect(Collectors.groupingBy(Product::getProductName, Collectors.counting()));