
本文深入探讨了如何利用 Java Stream API 高效地对数据进行分组、排序和转换。通过结合 `Collectors.groupingBy`、`Collectors.mapping` 和 `Collectors.collectingAndThen`,并巧妙运用 `LinkedHashSet` 和不同的排序策略(如 `Timsort`),我们将学习如何将原始数据集合转换为按指定顺序排列的、无重复的字符串集合,特别关注在处理大数据集时的性能优化。
在现代Java应用开发中,数据处理是核心任务之一。Java Stream API 提供了一种强大而声明式的方式来处理集合数据。本教程将聚焦于一个常见但具有挑战性的场景:给定一个包含订单详情的列表,我们需要根据订单ID对其进行分组,然后根据时间戳对每个组内的操作进行排序,并最终提取出按时间顺序排列的、不重复的操作名称集合。
假设我们有一个 OrderRow 类,它代表了订单中的一个具体操作:
import java.time.LocalDateTime;
public class OrderRow {
private Long orderId;
private String action;
private LocalDateTime timestamp;
public OrderRow(Long orderId, String action, LocalDateTime timestamp) {
this.orderId = orderId;
this.action = action;
this.timestamp = timestamp;
}
// Getters
public Long getOrderId() {
return orderId;
}
public String getAction() {
return action;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
@Override
public String toString() {
return "OrderRow{" +
"orderId=" + orderId +
", action='" + action + '\'' +
", timestamp=" + timestamp +
'}';
}
}我们有一组 OrderRow 数据,例如:
立即学习“Java免费学习笔记(深入)”;
OrderId Action Timestamp 3 Pay money 2015-05-27 12:48:47.000 3 Select Item 2015-05-27 12:44:47.000 1 Generate Payment 2015-05-27 12:55:47.000 2 Pay money 2015-05-27 12:48:47.000 2 Select Item 2015-05-27 12:44:47.000 2 Deliver 2015-05-27 12:55:47.000 1 Generate Invoice 2015-05-27 12:48:47.000 1 Create PO 2015-05-27 12:44:47.000 3 Deliver 2015-05-27 12:55:47.000
我们的目标是将其转换为以下 Map<Long, Set<String>> 形式:
[3] -> ["Select Item", "Pay money", "Deliver"] [1] -> ["Create PO", "Generate Invoice", "Generate Payment"] [2] -> ["Select Item", "Pay money", "Deliver"]
需要完成的操作包括:
一个常见的误区是尝试在 groupingBy 的下游收集器中直接使用 TreeSet 并提供一个基于 timestamp 的比较器。例如:
// 尝试一:无法得到 Map<Long, Set<String>> // orderRows.stream() // .collect(Collectors.groupingBy(OrderRow::getOrderId, // Collectors.mapping(Function.identity(), // Collectors.toCollection( // () -> new TreeSet<>(Comparator.comparing(OrderRow::getTimestamp)) // ))));
这种方法会产生 Map<Long, Set<OrderRow>>,而不是我们期望的 Map<Long, Set<String>>。更重要的是,TreeSet 虽然能保证元素有序,但其排序是基于元素本身的比较器。一旦我们将 OrderRow 映射为 String (即 action),TreeSet 将无法根据原始 OrderRow 的 timestamp 进行排序,因为它只知道 String。我们需要一个能够保留插入顺序的 Set 实现,同时确保插入的顺序是经过 timestamp 排序后的结果。
为了解决这个问题,我们需要更精细地控制 groupingBy 下游收集器的行为,特别是如何进行排序和最终的转换。
最直接的方法是在 groupingBy 之前,先对整个 OrderRow 流进行排序。这样,当 groupingBy 处理元素时,它们已经按照 timestamp 的全局顺序排列。
import java.util.*;
import java.util.stream.Collectors;
public class StreamGroupingAndSorting {
public static void main(String[] args) {
List<OrderRow> orderRows = Arrays.asList(
new OrderRow(3L, "Pay money", LocalDateTime.parse("2015-05-27T12:48:47")),
new OrderRow(3L, "Select Item", LocalDateTime.parse("2015-05-27T12:44:47")),
new OrderRow(1L, "Generate Payment", LocalDateTime.parse("2015-05-27T12:55:47")),
new OrderRow(2L, "Pay money", LocalDateTime.parse("2015-05-27T12:48:47")),
new OrderRow(2L, "Select Item", LocalDateTime.parse("2015-05-27T12:44:47")),
new OrderRow(2L, "Deliver", LocalDateTime.parse("2015-05-27T12:55:47")),
new OrderRow(1L, "Generate Invoice", LocalDateTime.parse("2015-05-27T12:48:47")),
new OrderRow(1L, "Create PO", LocalDateTime.parse("2015-05-27T12:44:47")),
new OrderRow(3L, "Deliver", LocalDateTime.parse("2015-05-27T12:55:47"))
);
Map<Long, Set<String>> actionsById = orderRows.stream()
// 1. 预先对整个流进行排序
.sorted(Comparator.comparing(OrderRow::getTimestamp))
// 2. 按 orderId 分组
.collect(Collectors.groupingBy(
OrderRow::getOrderId,
// 3. 将 OrderRow 映射为 action,并收集到 LinkedHashSet 以保持插入顺序
Collectors.mapping(
OrderRow::getAction,
Collectors.toCollection(LinkedHashSet::new)
)
));
System.out.println("Solution 1 (Pre-sorting): " + actionsById);
// 预期输出:
// {1=[Create PO, Generate Invoice, Generate Payment], 2=[Select Item, Pay money, Deliver], 3=[Select Item, Pay money, Deliver]}
}
}解析:
优点: 代码简洁,易于理解。 缺点: 如果数据集非常大,对整个流进行排序可能会消耗大量内存和CPU资源,尤其是在 groupingBy 键的数量相对较少时。
为了避免对整个流进行排序,我们可以在 groupingBy 内部,针对每个分组的数据进行独立的排序和转换。这需要使用 Collectors.collectingAndThen,它允许我们在下游收集器完成收集后,对结果进行最终的转换。
我们可以先将 OrderRow 对象收集到 TreeSet 中进行排序,然后再将其转换为 action 字符串的 LinkedHashSet。
// ... (OrderRow 和 orderRows 数据同上)
Map<Long, Set<String>> actionsByIdTreeSet = orderRows.stream()
.collect(Collectors.groupingBy(
OrderRow::getOrderId,
Collectors.collectingAndThen(
// 1. 将 OrderRow 收集到 TreeSet,根据 timestamp 排序
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(OrderRow::getTimestamp))),
// 2. 对 TreeSet 的结果进行后处理:映射为 action 并收集到 LinkedHashSet
set -> set.stream()
.map(OrderRow::getAction)
.collect(Collectors.toCollection(LinkedHashSet::new))
)
));
System.out.println("Solution 2.1 (TreeSet within groupingBy): " + actionsByIdTreeSet);解析:
性能考量: TreeSet 内部使用红黑树实现,每次插入操作的时间复杂度为 O(log N)。对于大量的元素,维护红黑树的开销可能比其他排序算法更高。
Java 8 Stream.sorted() 和 List.sort() 方法底层都使用了 Timsort 算法,它通常在实际数据中表现出 O(N log N) 的平均时间复杂度,并且在许多情况下比红黑树的维护更快。
// ... (OrderRow 和 orderRows 数据同上)
Map<Long, Set<String>> actionsByIdTimsort = orderRows.stream()
.collect(Collectors.groupingBy(
OrderRow::getOrderId,
Collectors.collectingAndThen(
// 1. 将 OrderRow 收集到 List
Collectors.mapping(
Function.identity(), Collectors.toList()
),
// 2. 对 List 进行后处理:排序、映射为 action 并收集到 LinkedHashSet
list -> list.stream()
.sorted(Comparator.comparing(OrderRow::getTimestamp)) // 使用 Timsort 排序
.map(OrderRow::getAction)
.collect(Collectors.toCollection(LinkedHashSet::new))
)
));
System.out.println("Solution 2.2 (Timsort within groupingBy): " + actionsByIdTimsort);解析:
性能考量: 相比 TreeSet,Timsort 在处理大数据量时通常具有更好的实际性能。然而,list.stream().sorted() 会创建一个新的中间数组来执行排序,这可能带来额外的内存开销。
为了进一步优化性能,我们可以避免在 finisher 函数中再次创建新的流并调用 sorted() 方法。相反,我们可以直接对收集到的 List 进行原地排序,然后将其流化并进行映射和收集。
import java.util.function.Function; // 确保导入 Function
// ... (OrderRow 和 orderRows 数据同上)
Map<Long, Set<String>> actionsByIdOptimized = orderRows.stream()
.collect(Collectors.groupingBy(
OrderRow::getOrderId,
Collectors.collectingAndThen(
// 1. 将 OrderRow 收集到 List
Collectors.mapping(
Function.identity(), Collectors.toList()
),
// 2. 对 List 进行原地排序,然后流化、映射为 action 并收集到 LinkedHashSet
list -> {
list.sort(Comparator.comparing(OrderRow::getTimestamp)); // 原地排序,避免创建新流
return list.stream()
.map(OrderRow::getAction)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
)
));
System.out.println("Solution 3 (Optimized In-place List Sorting): " + actionsByIdOptimized);解析:
性能考量: 这是在 groupingBy 内部实现排序和转换的最高效方法之一,因为它充分利用了 Timsort 的优势,并减少了不必要的对象创建和流操作。对于性能敏感的场景,这种方法是首选。
在处理复杂的数据分组、排序和转换需求时,Java Stream API 提供了强大的工具。选择哪种方法取决于具体的性能要求、数据量大小以及代码可读性偏好。
通过理解这些不同的策略和它们背后的机制,开发者可以根据具体需求,灵活选择最适合的 Java Stream 解决方案来高效处理数据。
以上就是Java Stream 高效分组、排序与转换:构建有序字符串集合的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号