Java8 Streams Collectors 使用

引言

在本文中,我們將向您展示如何使用 java8 流的 Collectors 對列表進(jìn)行分組、計(jì)數(shù)、求和和排序。

1. 分組、計(jì)數(shù)和排序

  1. 按列表分組并顯示列表的總數(shù)。
 List<String> items = Arrays.asList("apple", "apple", "banana",
        "apple", "orange", "banana", "papaya");

Map<String, Long> result = items.stream()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    System.out.println(result);

輸出:

{
    papaya=1, orange=1, banana=2, apple=3
}
  1. 添加排序
List<String> items = Arrays.asList("apple", "apple", "banana",
        "apple", "orange", "banana", "papaya");

Map<String, Long> result = items.stream()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    Map<String, Long> finalMap = new LinkedHashMap<>();

    result.entrySet().stream()
        .sorted(Entry.<String,Long>comparingByValue().reversed()).forEachOrdered(e->finalMap.put(e.getKey(),e.getValue()));

    System.out.println(finalMap);

輸出:

{
    apple=3, banana=2, papaya=1, orange=1
}

2.列出對象

按用戶定義的對象列表進(jìn)行“分組”的示例。

  1. 按名稱分組,并統(tǒng)計(jì)數(shù)量或求和。
public class Item {

    private String name;
    private int qty;
    private BigDecimal price;

    //constructors, getter/setters 
}
List<Item> items = Arrays.asList(
        new Item("apple", 10, new BigDecimal("9.99")),
        new Item("banana", 20, new BigDecimal("19.99")),
        new Item("orang", 10, new BigDecimal("29.99")),
        new Item("watermelon", 10, new BigDecimal("29.99")),
        new Item("papaya", 20, new BigDecimal("9.99")),
        new Item("apple", 10, new BigDecimal("9.99")),
        new Item("banana", 10, new BigDecimal("19.99")),
        new Item("apple", 20, new BigDecimal("9.99"))
    );

    Map<String, Long> couting = items.stream()
        .collect(Collectors.groupingBy(Item::getName, Collectors.counting()));

    System.out.println(couting);

    System.out.println("======");

    Map<String, Integer> sum = items.stream()
        .collect(Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getQty)));

    System.out.println(sum);

輸出:

{papaya=1, banana=2, apple=3, orang=1, watermelon=1}
======
{papaya=20, banana=30, apple=40, orang=10, watermelon=10}
  1. 按價格分組,Collectors.groupingBy and Collectors.mapping 的使用:
 List<Item> items = Arrays.asList(
        new Item("apple", 10, new BigDecimal("9.99")),
        new Item("banana", 20, new BigDecimal("19.99")),
        new Item("orang", 10, new BigDecimal("29.99")),
        new Item("watermelon", 10, new BigDecimal("29.99")),
        new Item("papaya", 20, new BigDecimal("9.99")),
        new Item("apple", 10, new BigDecimal("9.99")),
        new Item("banana", 10, new BigDecimal("19.99")),
        new Item("apple", 20, new BigDecimal("9.99"))
    );

System.out.println("=====>group by price:");
    // group by price
    Map<BigDecimal, List<Item>> groupByPriceMap = items.stream()
        .collect(Collectors.groupingBy(Item::getPrice));

    System.out.println(groupByPriceMap);

    Map<BigDecimal, Set<String>> collect = items.stream().collect(Collectors
        .groupingBy(Item::getPrice, Collectors.mapping(Item::getName, Collectors.toSet())));

    System.out.println("=====>group by + mapping to Set:");
    System.out.println(collect);

輸出:

=====>group by price:
{   19.99=[
        Item{name='banana', qty=20, price=19.99}, 
        Item{name='banana', qty=10, price=19.99}
        ], 
    29.99=[
        Item{name='orang', qty=10, price=29.99}, 
        Item{name='watermelon', qty=10, price=29.99}
        ], 
    9.99=[
        Item{name='apple', qty=10, price=9.99}, 
        Item{name='papaya', qty=20, price=9.99}, 
        Item{name='apple', qty=10, price=9.99}, 
        Item{name='apple', qty=20, price=9.99}
        ]
}
=====>group by + mapping to Set:
{   19.99=[banana], 
    29.99=[orang, watermelon], 
    9.99=[papaya, apple]
}

源碼見:java-8-demo

系列文章詳見:Java 8 教程

歡迎關(guān)注.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Java8 in action 沒有共享的可變數(shù)據(jù),將方法和函數(shù)即代碼傳遞給其他方法的能力就是我們平常所說的函數(shù)式...
    鐵牛很鐵閱讀 1,358評論 1 2
  • Stream 復(fù)雜API的操作 在第一部分stream part1中,我們已經(jīng)學(xué)習(xí)了部分stream的api來處理...
    bern85閱讀 578評論 0 3
  • Int Double Long 設(shè)置特定的stream類型, 提高性能,增加特定的函數(shù) 無存儲。stream不是一...
    patrick002閱讀 1,330評論 0 0
  • 1.流的基本概念 1.1 什么是流? 流是Java8引入的全新概念,它用來處理集合中的數(shù)據(jù),暫且可以把它理解為一種...
    升空的焰火閱讀 1,587評論 0 1
  • Stream API是Java8中處理集合的關(guān)鍵組件,提供了各種豐富的函數(shù)式操作。 Stream的創(chuàng)建 任何集合都...
    fengshunli閱讀 611評論 0 2

友情鏈接更多精彩內(nèi)容