Java8流:按分组并在新对象中存储和,以及合并映射

Java8流:按分组并在新对象中存储和,以及合并映射,java,lambda,java-8,java-stream,Java,Lambda,Java 8,Java Stream,我有一个班级排,例如: class Row { public Long id1; public String id2; public Long metric1; public Long metric2; public Stats getStats() { return new Stats(metric1, metric2); } } 和a类统计: class Stats{ public Long totalMetric1; pu

我有一个班级排,例如:

class Row {
   public Long id1;
   public String id2;
   public Long metric1;
   public Long metric2;

   public Stats getStats() {
      return new Stats(metric1, metric2);
   }
}
和a类统计:

class Stats{
    public Long totalMetric1;
    public Long totalMetric2;

    public void addMetric1(Long metric1) {
       this.totalMetric1 = this.totalMetric1 + metric1;
    }

    public void addMetric2(Long metric2) {
       this.totalMetric2 = this.totalMetric2 + metric2;
    }
}
我有一个行列表

List<Row> rowList;

我的建议是以比嵌套集合更简单的方式进行。在Row类中,添加

public Pair<Long,String> getIds() {
   return new Pair<>(id1,id2);
}
public Stats merge(Stats other) {
    return new Stats(totalMetric1+other.totalMetric1, totalMetric2 + other.totalMetric2);
}
然后写一些像

      Map<Pair<Long, String>, Stats> stats = rowList.stream().
              collect(Collectors.toMap(Row::getIds,Row::getStats, (s1,s2) -> s1.merge(s2)));
Map stats=rowList.stream()。
collect(Collectors.toMap(Row::getid,Row::getStats,(s1,s2)->s1.merge(s2));
如果你对番石榴不过敏(你也不应该过敏,至少对我来说,这是每个项目中都应该包含的一个不需要动脑筋的库),你可以用更优雅易读的语言编写它

      Table<Long, String, Stats> table = rowList.stream().
            collect(Tables.toTable(Row::getId1, Row::getId2, Row::getStats,(s1,s2) -> s1.merge(s2),HashBasedTable::create));
Table Table=rowList.stream()。
collect(Tables.toTable(Row::getId1,Row::getId2,Row::getStats,(s1,s2)->s1.merge(s2),HashBasedTable::create));

无需使用成对或嵌套映射。

您喜欢将
行的
ID映射到
字符串类型的
统计数据的
映射。什么是
String
类型的东西?你的
Stats
-构造函数在哪里接受两个参数?你真的想要一个映射,其中id1是键,值是一个额外的映射,id2是键,然后Stats对象是它的值?或者有一个带有复合键和stats作为其值的地图就足够了吗?(
Map
,其中
CompoundKey
甚至可以是串联的
String
?)@harmlez id2是字符串类型,因此我想在第一个映射中按id1分组,并将该映射的值按id2分组以获得第二个映射,id1的类型是
Long
,id2的类型是
String
@Roland我正在寻找你第一次描述的场景谢谢Artur,这对我很有用!我有一个后续问题,如果我需要在
中按字段添加另一个分组,有没有办法让
支持这一点?不,表只是二维矩阵,我不认为有相同质量的三维或n维等价物可用。然后,您需要开始在其中一个维度上使用元组(如Pair)。表对对对的好处是,您可以轻松地对行或列进行查询/迭代/etc。只要不需要这种类型的访问,就可以继续使用复合键(我将为超过2个元素的任何对象创建显式类)。
public Pair<Long,String> getIds() {
   return new Pair<>(id1,id2);
}
public Stats merge(Stats other) {
    return new Stats(totalMetric1+other.totalMetric1, totalMetric2 + other.totalMetric2);
}
      Map<Pair<Long, String>, Stats> stats = rowList.stream().
              collect(Collectors.toMap(Row::getIds,Row::getStats, (s1,s2) -> s1.merge(s2)));
      Table<Long, String, Stats> table = rowList.stream().
            collect(Tables.toTable(Row::getId1, Row::getId2, Row::getStats,(s1,s2) -> s1.merge(s2),HashBasedTable::create));