
Java Stream API 的 Collector 接口是执行终端操作的关键组件,它将流中的元素聚合成一个最终结果。Collector 接口定义了三个泛型类型:Collector<T, A, R>,其中:
自定义 Collector 的核心在于实现 Collector.of() 方法,它需要四个基本函数(可选地还可以指定特性):
理解 A 类型(累加器)的选择和实现是构建高效 Collector 的关键。A 类型可以是任何可变对象,包括原生数组、现有的并发工具类、匿名类,甚至是专门设计的自定义类。
在实现自定义 Collector 时,累加器类型 A 的选择至关重要。它决定了中间状态的存储方式以及操作的效率。
立即学习“Java免费学习笔记(深入)”;
对于简单的累加操作,例如求和,使用原生数组(如 int[])或 Java 并发包中的原子类(如 AtomicInteger)作为累加器类型是一种简洁高效的方式。这些类型本身就是可变的,可以直接在 accumulator 和 combiner 函数中进行修改。
示例:整数求和 Collector
以下示例展示了如何使用 int[] 和 AtomicInteger 来实现一个将流中整数求和的 Collector。
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collector;
import java.util.stream.Stream;
public class SumCollectors {
/**
* 使用 int[] 作为累加器实现整数求和。
* int[] 的第一个元素用于存储总和。
*
* @return 一个 Collector,将 Integer 流求和并返回 Integer。
*/
public static Collector<Integer, ?, Integer> sumWithIntArray() {
return Collector.of(
() -> new int[1], // supplier: 创建一个长度为1的int数组,用于存储和
(a, i) -> a[0] += i, // accumulator: 将元素i加到数组的第一个元素
(a, b) -> { a[0] += b[0]; return a; }, // combiner: 合并两个数组的和
a -> a[0], // finisher: 返回数组的第一个元素作为最终结果
Collector.Characteristics.UNORDERED // 标识此 Collector 的结果不受处理顺序影响
);
}
/**
* 使用 AtomicInteger 作为累加器实现整数求和。
* AtomicInteger 提供了线程安全的累加操作,适用于并行流。
*
* @return 一个 Collector,将 Integer 流求和并返回 Integer。
*/
public static Collector<Integer, ?, Integer> sumWithAtomicInteger() {
return Collector.of(
AtomicInteger::new, // supplier: 创建一个新的 AtomicInteger
AtomicInteger::addAndGet, // accumulator: 将元素加到 AtomicInteger 中
(a, b) -> { a.addAndGet(b.intValue()); return a; }, // combiner: 合并两个 AtomicInteger 的值
AtomicInteger::intValue, // finisher: 返回 AtomicInteger 的整数值
Collector.Characteristics.UNORDERED,
Collector.Characteristics.CONCURRENT // 标识此 Collector 可以并发执行
);
}
public static void main(String[] args) {
Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5);
Integer sum1 = numbers.collect(sumWithIntArray());
System.out.println("Sum using int[]: " + sum1); // Output: 15
Stream<Integer> numbers2 = Stream.of(10, 20, 30);
Integer sum2 = numbers2.collect(sumWithAtomicInteger());
System.out.println("Sum using AtomicInteger: " + sum2); // Output: 60
}
}注意事项:
当没有现成的类型能够满足复杂的累加需求时,可以考虑使用匿名类或局部内部类作为累加器 A。这种方式避免了创建独立的具名类,将累加器的实现细节封装在 Collector 内部,提高了代码的局部性和可读性。
示例:收集具有最大值的键
假设我们需要从 Map.Entry<K, Integer> 的流中,收集所有对应值为最大值的键。这里累加器需要同时存储当前最大值和对应的键列表。
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Stream;
public class MaxKeysCollector {
/**
* 使用 AbstractMap.SimpleEntry 作为累加器,收集具有最大值的键。
* SimpleEntry 的 key 存储键列表,value 存储当前最大值。
*
* @param <K> 键的类型
* @return 一个 Collector,收集 Map.Entry 流中最大值对应的键列表。
*/
public static <K> Collector<Map.Entry<K, Integer>, ?, List<K>> keysToMaximumWithSimpleEntry() {
return Collector.of(
// supplier: 创建一个 SimpleEntry,键为新 ArrayList,值为 Integer.MIN_VALUE
() -> new AbstractMap.SimpleEntry<>(new ArrayList<K>(), Integer.MIN_VALUE),
// accumulator: 根据当前元素更新最大值和键列表
(current, next) -> {
int max = current.getValue();
int value = next.getValue();
if (value >= max) {
if (value > max) { // 发现更大的值,清空旧列表并更新最大值
current.setValue(value);
current.getKey().clear();
}
current.getKey().add(next.getKey()); // 添加当前键
}
},
// combiner: 合并两个累加器
(a, b) -> {
int maxA = a.getValue();
int maxB = b.getValue();
if (maxA < maxB) return b; // b 的最大值更大,返回 b
if (maxA == maxB) a.getKey().addAll(b.getKey()); // 最大值相同,合并键列表
return a; // a 的最大值更大或相同,返回 a
},
// finisher: 返回 SimpleEntry 中的键列表
Map.Entry::getKey
);
}
/**
* 使用匿名类作为累加器,收集具有最大值的键。
* 匿名类可以更灵活地定义内部状态。
*
* @param <K> 键的类型
* @return 一个 Collector,收集 Map.Entry 流中最大值对应的键列表。
*/
public static <K> Collector<Map.Entry<K, Integer>, ?, List<K>> keysToMaximumWithAnonymousClass() {
return Collector.of(
// supplier: 创建一个匿名对象作为累加器
() -> new Object() {
int max = Integer.MIN_VALUE;
final List<K> keys = new ArrayList<>();
},
// accumulator: 根据当前元素更新匿名对象的状态
(current, next) -> {
int value = next.getValue();
if (value >= current.max) {
if (value > current.max) {
current.max = value;
current.keys.clear();
}
current.keys.add(next.getKey());
}
},
// combiner: 合并两个匿名对象的状态
(a, b) -> {
if (a.max < b.max) return b;
if (a.max == b.max) a.keys.addAll(b.keys);
return a;
},
// finisher: 返回匿名对象中的键列表
a -> a.keys
);
}
public static void main(String[] args) {
Map<String, Integer> data = Map.of("A", 10, "B", 20, "C", 20, "D", 5);
Stream<Map.Entry<String, Integer>> entryStream = data.entrySet().stream();
List<String> maxKeys1 = entryStream.collect(keysToMaximumWithSimpleEntry());
System.out.println("Max keys using SimpleEntry: " + maxKeys1); // Output: [B, C]
Map<String, Integer> data2 = Map.of("X", 100, "Y", 50, "Z", 100);
Stream<Map.Entry<String, Integer>> entryStream2 = data2.entrySet().stream();
List<String> maxKeys2 = entryStream2.collect(keysToMaximumWithAnonymousClass());
System.out.println("Max keys using Anonymous Class: " + maxKeys2); // Output: [X, Z]
}
}注意事项:
尽管前面两种方法非常灵活,但在某些情况下,如果累加器需要承载更复杂的业务逻辑或在多个 Collector 中复用,创建一个独立的具名类作为累加器类型 A 也是一个合理的选择。这种方式提供了更好的封装性和可维护性。
示例:自定义 SumCollector 类
在原始问题中,SumCollector 类就是一个典型的例子,它封装了求和的逻辑。
public static class SumCollectorAccumulator {
Integer value;
public SumCollectorAccumulator(Integer value) {
this.value = value;
}
public static SumCollectorAccumulator supply() {
return new SumCollectorAccumulator(0);
}
public void accumulate(Integer next) {
value += next;
}
public SumCollectorAccumulator combine(SumCollectorAccumulator other) {
return new SumCollectorAccumulator(value + other.value);
}
public String finish(){
return Integer.toString(value);
}
}
// 使用自定义累加器类创建 Collector
public static Collector<Integer, SumCollectorAccumulator, String> customSumCollector() {
return Collector.of(
SumCollectorAccumulator::supply,
SumCollectorAccumulator::accumulate,
SumCollectorAccumulator::combine,
SumCollectorAccumulator::finish
);
}注意事项:
总之,Java Collector 提供了强大的灵活性来处理各种数据聚合需求。通过理解其泛型类型、Collector.of() 方法的各个参数以及累加器类型的选择策略,开发者可以构建出高效、可读且功能强大的自定义数据收集器。关键在于根据具体的聚合逻辑和性能要求,选择最合适的累加器实现方式。
以上就是Java Stream Collector 深度解析:自定义累加器与实现技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号