
引言
在数据处理中,我们经常需要对集合中的元素进行分组和聚合操作。当数据以非结构化的 string[] 数组形式存在,并且分组条件涉及数组中的多个元素时,传统的 collectors.groupingby 可能会变得复杂,尤其是在需要将聚合结果重新格式化为原始数据结构时。本教程将展示如何利用自定义键对象(key)结合 java stream api,优雅地解决这一问题。
假设我们有一个 List
- 根据数组中特定位置的元素(例如,索引 0、1、3 和 5)进行分组。
- 对每个分组内,将另一个特定位置的元素(例如,索引 6)解析为数值并进行求和。
- 最终生成一个新的 List
,其中每个数组代表一个分组的聚合结果。
初始数据结构与需求
考虑以下 List
ListdataLines = List.of( new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4055", "84M", "-101.87", "0"}, new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4055", "120M", "-102.48", "0"}, new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4055", "60M", "-103.75", "0"}, new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4055", "120M", "-10.8", "0"}, new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4055", "60M", "-110.39", "0"}, new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4055", "120M", "-10.8", "0"}, new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "CZK", "12670012.4055", "60M", "-103.75", "0"}, new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4066", "20M", "-10.8", "0"} );
我们希望根据 0th、1st、3rd 和 5th 元素相同的规则进行分组,并对 6th 元素(表示金额)进行求和。最终输出的 List
["2002","BRBTSS","BRSTNCNTF212","BRL","12670012.4055","84M","-101.87","0"], ["2002","BRBTSS","BRSTNCNTF212","BRL","12670012.4055","120M","-124124.08000000000001","0"], // 原始3个120M的数据汇总 ["2002","BRBTSS","BRSTNCNTF212","BRL","12670012.4055","60M","-214.14","0"], // 原始2个60M的数据汇总 ["2002","BRBTSS","BRSTNCNTF212","CZK","12670012.4055","60M","-103.75","0"], ["2002","BRBTSS","BRSTNCNTF212","BRL","12670012.4066","20M","-10.8","0"]
直接使用多层 Collectors.groupingBy 会生成一个深度嵌套的 Map 结构,这虽然能完成分组和求和,但将其扁平化并转换回 List
立即学习“Java免费学习笔记(深入)”;
解决方案:自定义键对象
为了更优雅地实现多字段分组,我们可以创建一个自定义的键对象(Key 类或 Java 16+ 的 record),它封装了所有用于分组的字段,并正确实现 equals() 和 hashCode() 方法。Collectors.groupingBy 内部依赖这两个方法来识别“相同”的键。
1. 定义 Key 对象
我们将使用 record 来实现 Key,因为它提供了简洁的语法来自动生成构造函数、访问器、equals() 和 hashCode() 方法。如果您的 Java 版本低于 16,可以使用普通的 class 实现。
使用 Java 16+ record:
import java.util.Objects;
public record Key(String s0, String s1, String s2, String s3, String s4, String s5, String s7) {
// 辅助构造函数,方便从 String[] 创建 Key 实例
public Key(String[] line) {
this(line[0], line[1], line[2], line[3], line[4], line[5], line[7]);
}
// 重新定义 equals 方法,只比较用于分组的字段 (s0, s1, s3, s5)
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
return Objects.equals(s0, key.s0) && Objects.equals(s1, key.s1) && Objects.equals(s3, key.s3) && Objects.equals(s5, key.s5);
}
// 重新定义 hashCode 方法,只包含用于分组的字段 (s0, s1, s3, s5)
@Override
public int hashCode() {
return Objects.hash(s0, s1, s3, s5);
}
// 将 Key 对象和聚合后的 s6 值转换回 String[]
public String[] toArray(Double s6) {
return new String[]{s0, s1, s2, s3, s4, s5, String.valueOf(s6), s7};
}
}使用 Java class (兼容所有版本):
import java.util.Objects;
public class Key {
private final String s0;
private final String s1;
private final String s2;
private final String s3;
private final String s4;
private final String s5;
private final String s7;
public Key(String s0, String s1, String s2, String s3, String s4, String s5, String s7) {
this.s0 = s0;
this.s1 = s1;
this.s2 = s2;
this.s3 = s3;
this.s4 = s4;
this.s5 = s5;
this.s7 = s7;
}
// 辅助构造函数,方便从 String[] 创建 Key 实例
public Key(String[] line) {
this(line[0], line[1], line[2], line[3], line[4], line[5], line[7]);
}
// Getter 方法 (如果需要,但对于内部键对象通常不是必需的)
public String getS0() { return s0; }
public String getS1() { return s1; }
public String getS2() { return s2; }
public String getS3() { return s3; }
public String getS4() { return s4; }
public String getS5() { return s5; }
public String getS7() { return s7; }
// 重新定义 equals 方法,只比较用于分组的字段 (s0, s1, s3, s5)
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
return Objects.equals(s0, key.s0) && Objects.equals(s1, key.s1) && Objects.equals(s3, key.s3) && Objects.equals(s5, key.s5);
}
// 重新定义 hashCode 方法,只包含用于分组的字段 (s0, s1, s3, s5)
@Override
public int hashCode() {
return Objects.hash(s0, s1, s3, s5);
}
// 将 Key 对象和聚合后的 s6 值转换回 String[]
public String[] toArray(Double s6) {
return new String[]{s0, s1, s2, s3, s4, s5, String.valueOf(s6), s7};
}
}equals() 和 hashCode() 的重要性:equals() 和 hashCode() 方法是 Map 和 Set 等集合类型正确工作的基石。
- equals() 方法定义了两个对象何时被认为是“相等”的。在这里,我们只比较 s0, s1, s3, s5 这四个字段,因为它们是我们的分组依据。
- hashCode() 方法返回对象的哈希码。根据 Java 规范,如果两个对象 equals 返回 true,那么它们的 hashCode 必须相同。因此,hashCode() 也必须只基于 s0, s1, s3, s5 这四个字段来计算。
Key 对象中的其他字段(s2, s4, s7)虽然不参与分组,但它们在 Key 构造时被保留,以便在最终构建 String[] 结果时能够还原原始数据。
2. 使用 Stream API 进行分组和聚合
有了自定义的 Key 对象,我们现在可以利用 Java Stream API 来实现分组和求和:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class DataAggregator {
public static void main(String[] args) {
List dataLines = List.of(
new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4055", "84M", "-101.87", "0"},
new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4055", "120M", "-102.48", "0"},
new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4055", "60M", "-103.75", "0"},
new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4055", "120M", "-10.8", "0"},
new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4055", "60M", "-110.39", "0"},
new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4055", "120M", "-10.8", "0"},
new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "CZK", "12670012.4055", "60M", "-103.75", "0"},
new String[]{"2002", "BRBTSS", "BRSTNCNTF212", "BRL", "12670012.4066", "20M", "-10.8", "0"}
);
List newDataLine = dataLines.stream()
.collect(Collectors.groupingBy(
Key::new, // 使用 Key::new 作为分类函数,将 String[] 转换为 Key 对象
Collectors.summingDouble(s -> Double.parseDouble(s[6])) // 对每个分组内的 String[] 的第6个元素求和
)) // 结果是一个 Map
.entrySet().stream() // 将 Map 转换为 Stream>
.map(entry -> entry.getKey().toArray(entry.getValue())) // 对每个 Entry,使用 Key 的 toArray 方法重构 String[]
.collect(Collectors.toList()); // 收集为 List
// 打印结果
newDataLine.forEach(arr -> System.out.println(Arrays.toString(arr)));
}
} 代码解析:
- dataLines.stream(): 创建原始数据的 Stream。
- collect(Collectors.groupingBy(Key::new, ...)): 这是核心的分组操作。
- Key::new: 作为分类函数(classifier),它将每个 String[] 元素转换为一个 Key 对象。groupingBy 会根据这些 Key 对象的 equals() 和 hashCode() 方法来决定哪些元素属于同一个组。
- Collectors.summingDouble(s -> Double.parseDouble(s[6])): 作为下游收集器(downstream collector),它对每个分组内的元素执行聚合操作。这里,它将每个 String[] 的第 6 个元素解析为 double 类型并进行求和。
- 此步骤的结果是一个 Map
,其中 Key 是分组依据,Double 是对应分组的第 6 个元素的总和。
- .entrySet().stream(): 将 Map 的 entrySet 转换为 Stream,以便我们可以遍历每个 Key-Value 对。
- .map(entry -> entry.getKey().toArray(entry.getValue())): 对 Stream 中的每个 Map.Entry 执行映射操作。
- entry.getKey() 获取分组的 Key 对象。
- entry.getValue() 获取该分组的聚合结果(求和后的 Double 值)。
- entry.getKey().toArray(entry.getValue()) 调用 Key 对象的 toArray 方法,将 Key 中保存的原始字段和聚合后的 Double 值组合,重新构建一个新的 String[]。
- .collect(Collectors.toList()): 将最终的 String[] 收集到一个 List 中。
示例输出
运行上述代码,将得到以下输出:
[2002, BRBTSS, BRSTNCNTF212, BRL, 12670012.4055, 84M, -101.87, 0] [2002, BRBTSS, BRSTNCNTF212, BRL, 12670012.4055, 60M, -214.14, 0] [2002, BRBTSS, BRSTNCNTF212, BRL, 12670012.4055, 120M, -124124.08000000000001, 0] [2002, BRBTSS, BRSTNCNTF212, BRL, 12670012.4066, 20M, -10.8, 0] [2002, BRBTSS, BRSTNCNTF212, CZK, 12670012.4055, 60M, -103.75, 0]
可以看到,原始数据中 0th, 1st, 3rd, 5th 字段相同的行被成功分组,并且它们的 6th 字段被求和。例如,有三行数据的分组键为 ("2002", "BRBTSS", "BRL", "120M"),它们的 6th 字段分别是 -102.48, -10.8, -10.8,求和结果为 -124124.08。
注意事项与最佳实践
-
数据结构优化:避免 List
尽管本教程解决了 List 的分组问题,但在实际项目中,强烈建议将 String[] 替换为自定义的 Java 对象(POJO 或 record)。例如,可以定义一个 DataEntry 类,其中包含 year、id1、id2、currency、value1、timePeriod、amount、status 等有意义的字段。 这样做的好处是: - 类型安全: 字段具有明确的类型(int, String, double 等),避免了 String 到其他类型的频繁转换和潜在的 NumberFormatException。
- 可读性: 通过字段名而非数组索引访问数据,代码更易理解和维护。
- 健壮性: 避免因数组索引越界或数据格式不一致导致的问题。 如果使用自定义对象,Key 对象可以直接引用这些对象的属性,而不是通过数组索引。
-
浮点数精度问题:使用 BigDecimal 在处理金额、汇率等需要高精度的浮点数计算时,double 类型可能存在精度问题。尽管 Collectors.summingDouble() 在一定程度上缓解了这些问题,但最佳实践是使用 java.math.BigDecimal。 如果使用 BigDecimal,你需要:
Java record 的优势 Java 16 引入的 record 类型非常适合作为这种分组操作中的键对象。它自动生成了构造函数、访问器方法、equals() 和 hashCode() 方法,大大减少了样板代码。本教程中,我们通过重写 equals() 和 hashCode() 来定制分组逻辑,同时保留了 record 的简洁性。
总结
通过本教程,我们学习了如何利用自定义键对象结合 Java Stream API 来解决 List










