partitioningBy 与计数
使用 partitioningBy 将流拆分为两组,并使用 counting 统计元素数量
partitioningBy 与计数 是 CoddyKit 上的免费 Java Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Java Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Java Academy 课程共包含 4 节课。
partitioningBy 基础
Collectors.partitioningBy(predicate) 会将流准确地拆分为两个分组——true 和 false——并返回一个 Map<Boolean, List<T>>。
import java.util.*;
import java.util.stream.*;
List<Integer> nums = List.of(1,2,3,4,5,6,7,8,9,10);
Map<Boolean, List<Integer>> evenOdd =
nums.stream().collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println(evenOdd.get(true)); // [2, 4, 6, 8, 10]
System.out.println(evenOdd.get(false)); // [1, 3, 5, 7, 9]partitioningBy 与 filter 的比较
与 filter 不同,partitioningBy 会同时保留两个分组——当您需要分区的两部分时非常有用。
record Student(String name, int score) {}
List<Student> students = List.of(
new Student("Alice",90), new Student("Bob",55),
new Student("Carol",72), new Student("Dave",48)
);
Map<Boolean, List<Student>> result =
students.stream().collect(
Collectors.partitioningBy(s -> s.score() >= 60)
);
System.out.println("Passed: " + result.get(true).size());
System.out.println("Failed: " + result.get(false).size());partitioningBy 的下游收集器
与 groupingBy 一样,将 partitioningBy 与下游收集器组合使用:
Map<Boolean, Long> passFailCount =
students.stream().collect(
Collectors.partitioningBy(
s -> s.score() >= 60,
Collectors.counting()
)
);
System.out.println("Passed: " + passFailCount.get(true));
System.out.println("Failed: " + passFailCount.get(false));counting() 收集器
Collectors.counting() 会统计流(或下游分组)中的元素数量。它相当于 reducing(0L, e -> 1L, Long::sum) 的便捷写法。
long count = Stream.of("a","bb","ccc","dddd")
.collect(Collectors.counting());
System.out.println(count); // 4
// Same as:
long count2 = Stream.of("a","bb","ccc","dddd").count();
// Use counting() as a downstream; use .count() as a terminal op将 counting() 用作下游收集器
counting() 作为 groupingBy/partitioningBy 的下游收集器时尤其有用:
List<String> words = List.of("cat","dog","car","door","cup","dune");
Map<Character, Long> byFirstLetter =
words.stream().collect(
Collectors.groupingBy(w -> w.charAt(0), Collectors.counting())
);
byFirstLetter.forEach((c, n) -> System.out.println(c + ": " + n));
// c: 3, d: 3将分区转换为名称
使用 mapping 下游收集器提取每个分区中的名称:
Map<Boolean, List<String>> namesByPass =
students.stream().collect(
Collectors.partitioningBy(
s -> s.score() >= 60,
Collectors.mapping(Student::name, Collectors.toList())
)
);
System.out.println("Passed: " + namesByPass.get(true));
System.out.println("Failed: " + namesByPass.get(false));将 counting 与 summarizingInt 组合使用
Collectors.summarizingInt() 一次遍历即可计算数量、总和、最小值、最大值和平均值:
IntSummaryStatistics stats =
students.stream().collect(
Collectors.summarizingInt(Student::score)
);
System.out.println("Count: " + stats.getCount());
System.out.println("Average: " + stats.getAverage());
System.out.println("Max: " + stats.getMax());
System.out.println("Min: " + stats.getMin());实际应用:A/B 测试分组
将用户分到对照组和处理组,用于 A/B 测试:
record User(String id, boolean isInTreatment) {}
List<User> users = List.of(
new User("u1",true), new User("u2",false),
new User("u3",true), new User("u4",false)
);
Map<Boolean, Long> split =
users.stream().collect(
Collectors.partitioningBy(User::isInTreatment, Collectors.counting())
);
System.out.println("Treatment: " + split.get(true)); // 2
System.out.println("Control: " + split.get(false)); // 2使用 groupingBy + counting 构建频率映射
统计每个元素出现的次数(单词频率映射):
List<String> words2 = List.of("apple","banana","apple","cherry","banana","apple");
Map<String, Long> freq =
words2.stream().collect(
Collectors.groupingBy(w -> w, Collectors.counting())
);
freq.entrySet().stream()
.sorted(Map.Entry.<String,Long>comparingByValue().reversed())
.forEach(e -> System.out.println(e.getKey()+": "+e.getValue()));partitioningBy 始终返回两个键
与 groupingBy 不同,partitioningBy 始终返回同时包含 true 和 false 键的映射——即使其中一个分组为空。这可以避免在 map.get(true) 中出现 NullPointerExceptions。
List<Integer> allEven = List.of(2,4,6);
Map<Boolean, List<Integer>> m =
allEven.stream().collect(Collectors.partitioningBy(n -> n % 2 != 0));
System.out.println(m.get(true)); // [] (empty, not null)
System.out.println(m.get(false)); // [2, 4, 6]性能:单次遍历
partitioningBy 和 counting 都只需遍历流一次——复杂度为 O(n)。它们不需要排序。因此,与调用两次 filter 或在分组前排序相比,效率高得多。
快速检查
Collectors.partitioningBy(predicate) 的返回类型是什么?
回顾:partitioningBy 和 counting
要点回顾:
- partitioningBy 会准确拆分为两个分组(真/假)
- 两个键始终存在——不像 groupingBy 那样存在 NPE 风险
- counting() 用于统计元素数量;可将其用作分组的下游收集器
- summarizingInt/Long/Double 一次遍历即可得到数量、总和、最小值、最大值和平均值
- 所有操作都只需进行一次 O(n) 流遍历
常见问题解答
「partitioningBy 与计数」课时是免费的吗?
是的 — 「partitioningBy 与计数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Java Academy 课程的其余内容,请升级到 CoddyKit PRO。 Java Academy 课程共包含 4 节课。
「partitioningBy 与计数」这节课中我会学到什么?
使用 partitioningBy 将流拆分为两组,并使用 counting 统计元素数量 你通过在浏览器中直接运行的动手代码来练习 Java Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Java Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Java Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「partitioningBy 与计数」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Java Academy 课中编写并运行代码吗?
能。每节 Java Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- groupingBy:元素分类
- partitioningBy 与计数
- toMap、joining 与 summarizing
- 构建自定义收集器