
在数据处理中,我们经常需要对集合中的元素进行分组和聚合操作。当数据以非结构化的 string[] 数组形式存在,并且分组条件涉及数组中的多个元素时,传统的 collectors.groupingby 可能会变得复杂,尤其是在需要将聚合结果重新格式化为原始数据结构时。本教程将展示如何利用自定义键对象(key)结合 java stream api,优雅地解决这一问题。
假设我们有一个 List<String[]>,其中每个 String[] 代表一行数据,包含多个字符串字段。我们的目标是:
考虑以下 List<String[]> 示例数据:
List<String[]> 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"}
);我们希望根据 0th、1st、3rd 和 5th 元素相同的规则进行分组,并对 6th 元素(表示金额)进行求和。最终输出的 List<String[]> 应包含每个分组的聚合结果,例如:
["2002","BRBTSS","BRSTNCNTF212","BRL","12670012.4055","84M","-101.87","0"], ["2002","BRBTSS","BRSTNCNTF212","BRL","12670012.4055","120M","-124.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<String[]> 会非常繁琐。
立即学习“Java免费学习笔记(深入)”;
为了更优雅地实现多字段分组,我们可以创建一个自定义的键对象(Key 类或 Java 16+ 的 record),它封装了所有用于分组的字段,并正确实现 equals() 和 hashCode() 方法。Collectors.groupingBy 内部依赖这两个方法来识别“相同”的键。
我们将使用 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 等集合类型正确工作的基石。
Key 对象中的其他字段(s2, s4, s7)虽然不参与分组,但它们在 Key 构造时被保留,以便在最终构建 String[] 结果时能够还原原始数据。
有了自定义的 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<String[]> 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<String[]> newDataLine = dataLines.stream()
.collect(Collectors.groupingBy(
Key::new, // 使用 Key::new 作为分类函数,将 String[] 转换为 Key 对象
Collectors.summingDouble(s -> Double.parseDouble(s[6])) // 对每个分组内的 String[] 的第6个元素求和
)) // 结果是一个 Map<Key, Double>
.entrySet().stream() // 将 Map 转换为 Stream<Map.Entry<Key, Double>>
.map(entry -> entry.getKey().toArray(entry.getValue())) // 对每个 Entry,使用 Key 的 toArray 方法重构 String[]
.collect(Collectors.toList()); // 收集为 List<String[]>
// 打印结果
newDataLine.forEach(arr -> System.out.println(Arrays.toString(arr)));
}
}代码解析:
运行上述代码,将得到以下输出:
[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, -124.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,求和结果为 -124.08。
数据结构优化:避免 List<String[]> 尽管本教程解决了 List<String[]> 的分组问题,但在实际项目中,强烈建议将 String[] 替换为自定义的 Java 对象(POJO 或 record)。例如,可以定义一个 DataEntry 类,其中包含 year、id1、id2、currency、value1、timePeriod、amount、status 等有意义的字段。 这样做的好处是:
浮点数精度问题:使用 BigDecimal 在处理金额、汇率等需要高精度的浮点数计算时,double 类型可能存在精度问题。尽管 Collectors.summingDouble() 在一定程度上缓解了这些问题,但最佳实践是使用 java.math.BigDecimal。 如果使用 BigDecimal,你需要:
Java record 的优势 Java 16 引入的 record 类型非常适合作为这种分组操作中的键对象。它自动生成了构造函数、访问器方法、equals() 和 hashCode() 方法,大大减少了样板代码。本教程中,我们通过重写 equals() 和 hashCode() 来定制分组逻辑,同时保留了 record 的简洁性。
通过本教程,我们学习了如何利用自定义键对象结合 Java Stream API 来解决 List<String[]> 类型数据的多字段分组和数值聚合问题。这种方法比嵌套 Collectors.groupingBy 更清晰、更易于管理,并且能够方便地将聚合结果转换回所需的 List<String[]>
以上就是Java Stream 多字段分组与数值汇总教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号