當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Collectors groupingBy()用法及代碼示例

Java中的Collectors類的groupingBy()方法用於按某些屬性對對象進行分組並將結果存儲在Map實例中。為了使用它,我們總是需要指定一個屬性來執行分組。此方法提供的函數類似於SQL的GROUP BY子句。

用法:

public static Collector<T, ?, Map<K, List>> groupingBy(Function classifier)



類型參數:此方法采用兩個類型參數:

  • T-這是輸入元素的類型。
  • K-這是要轉換的輸入元素的類型。

參數:此方法接受兩個強製性參數:

  • Function-這是要應用於輸入元素的屬性。
  • Classifier-它用於將輸入元素映射到目標映射中。

返回值:它返回一個Collector作為Map。

下麵是groupingBy()方法的程序實現:

程序1:

// Java program to demonstrate 
// Collectors groupingBy() method 
  
import java.util.*; 
import java.util.function.Function; 
import java.util.stream.Collectors; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Get the List 
        List<String> g 
            = Arrays.asList("geeks", "for", "geeks"); 
  
        // Collect the list as map 
        // by groupingBy() method 
        Map<String, Long> result 
            = g.stream().collect( 
                Collectors.groupingBy( 
                    Function.identity(), 
                    Collectors.counting())); 
  
        // Print the result 
        System.out.println(result); 
    } 
}
輸出:
{geeks=2, for=1}

參考: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-



相關用法


注:本文由純淨天空篩選整理自suman_ptnl大神的英文原創作品 Collectors groupingBy() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。