Java Stream API groupingBy()介紹
groupingBy()是Stream API中最強大的收集器Collector之一,提供與SQL的GROUP BY子句類似的功能。
使用形式如下:
.collect(groupingBy(...));
需要指定一個屬性才能使用,通過該屬性執行分組。我們通過提供功能介面的實現來實現這一點 - 通常通過傳遞lambda表示式。
例如,如果我們想按長度對字串進行分組,我們可以通過將String :: length傳遞給groupingBy()來實現:
List<String> strings = List.of("a", "bb", "cc", "ddd");
Map<Integer, List<String>> result = strings.stream()
.collect(groupingBy(String::length));
System.out.println(result); // {1=[a], 2=[bb, cc], 3=[ddd]}
分組到自定義Map實現
如果需要提供自定義Map實現,可以使用提供的groupingBy()過載來實現:
List<String> strings = List.of("a", "bb", "cc", "ddd");
TreeMap<Integer, List<String>> result = strings.stream()
.collect(groupingBy(String::length, TreeMap::new, toList()));
System.out.println(result); // {1=[a], 2=[bb, cc], 3=[ddd]}
提供自定義的下一個Collection
如果需要將分組元素儲存在自定義集合中,可以使用toCollection()收集器來實現。
例如,如果要在TreeSet例項中對元素進行分組,然後輸出到一個新的Collection,則可以這樣簡單:
List<String> strings = List.of("a", "bb", "cc", "ddd");
Map<Integer, TreeSet<String>> result = strings.stream()
.collect(groupingBy(String::length, toCollection(TreeSet::new)));
System.out.println(result); // {1=[a], 2=[bb, cc], 3=[ddd]}
分組計數
如果您只想知道分組元素的數量,提供自定義counting()j就可以:
List<String> strings = List.of("a", "bb", "cc", "ddd");
Map<Integer, Long> result = strings.stream()
.collect(groupingBy(String::length, counting()));
System.out.println(result); // {1=1, 2=2, 3=1}
將每個組轉為字串
如果需要對元素進行分組併為每個組建立單個String表示,可以使用join()來實現:
List<String> strings = List.of("a", "bb", "cc", "ddd");
Map<Integer, String> result = strings.stream()
.collect(groupingBy(String::length, joining(",", "[", "]")));
System.out.println(result); // {1=[a], 2=[bb,cc], 3=[ddd]}
分組和過濾條目
從分組結果中排除某些條目。這可以使用filtering()收集器來實現:
List<String> strings = List.of("a", "bb", "cc", "ddd");
Map<Integer, List<String>> result = strings.stream()
.collect(groupingBy(String::length, filtering(s -> !s.contains("c"), toList())));
System.out.println(result); // {1=[a], 2=[bb], 3=[ddd]}
分組和計算每組平均值
如果需要派生每組條目的平均屬性,那麼有一些方便的收集器:
averagingInt()
averagingLong()
averagingDouble()
List<String> strings = List.of("a", "bb", "cc", "ddd");
Map<Integer, Double> result = strings.stream()
.collect(groupingBy(String::length, averagingInt(String::hashCode)));
System.out.println(result); // {1=97.0, 2=3152.0, 3=99300.0}
分組和計算每組的總和
如果要對分組條目進行累計總和:
summingInt()
summingLong()
summingDouble()
List<String> strings = List.of("a", "bb", "cc", "ddd");
Map<Integer, Integer> result = strings.stream()
.collect(groupingBy(String::length, summingInt(String::hashCode)));
System.out.println(result); // {1=97, 2=6304, 3=99300}
reducing縮減操作
List<String> strings = List.of("a", "bb", "cc", "ddd");
Map<Integer, List<Character>> result = strings.stream()
.map(toStringList())
.collect(groupingBy(List::size, reducing(List.of(), (l1, l2) -> Stream.concat(l1.stream(), l2.stream())
.collect(Collectors.toList()))));
System.out.println(result); // {1=[a], 2=[b, b, c, c], 3=[d, d, d]}
計算最大最小值
List<String> strings = List.of("a", "bb", "cc", "ddd");
Map<Integer, Optional<String>> result = strings.stream()
.collect(groupingBy(String::length, Collectors.maxBy(Comparator.comparing(String::toUpperCase))));
System.out.println(result); // {1=Optional[a], 2=Optional[cc], 3=Optional[ddd]}
組合Collector
示例#1
假設我們有一個字串列表,並希望獲得與長度大於1的大寫字串相關聯的字串長度的對映,並將它們收集到TreeSet例項中。
var result = strings.stream()
.collect(
groupingBy(String::length,
mapping(String::toUpperCase,
filtering(s -> s.length() > 1,
toCollection(TreeSet::new)))));
//result
{1=[], 2=[BB, CC], 3=[DDD]}
例#2
指定字串列表,按匹配長度對它們進行分組,轉換為字元列表,展平獲取的列表,僅保留具有非零長度的不同元素,並最終通過應用字串連線來減少它們。
var result = strings.stream()
.collect(
groupingBy(String::length,
mapping(toStringList(),
flatMapping(s -> s.stream().distinct(),
filtering(s -> s.length() > 0,
mapping(String::toUpperCase,
reducing("", (s, s2) -> s + s2)))))
));
//result
{1=A, 2=BC, 3=D}