【问题标题】:Java 8 Stream: Defining collectors based on other collectorsJava 8 Stream:基于其他收集器定义收集器
【发布时间】:2017-12-05 03:02:38
【问题描述】:

我是使用 Java 8 Stream API 的新手,但我希望用它来解决以下问题。假设我有一个名为 InputRecord 的 POJO,其中包含 namefieldAfieldB 属性,它们可以表示以下每行记录:

name | fieldA | fieldB
----------------------
A    | 100    | 1.1
A    | 150    | 2.0
B    | 200    | 1.5
A    | 120    | 1.3

InputRecord 看起来像:

public class InputRecord {
    private String name;
    private Integer fieldA;
    private BigDecimal fieldB;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getFieldA() {
        return fieldA;
    }

    public void setFieldA(Integer fieldA) {
        this.fieldA = fieldA;
    }

    public BigDecimal getFieldB() {
        return fieldB;
    }

    public void setFieldB(BigDecimal fieldB) {
        this.fieldB = fieldB;
    }
}

以上这四条记录需要合并成两条按名称分组的记录,其中:

  1. 属性fieldA 被求和
  2. 属性fieldB 被求和
  3. 合并的记录包括一个fieldC 属性,它是fieldAfieldB 的累加和相乘的结果。

因此上面的结果是:

name | sumOfFieldA | sumOfFieldB | fieldC (sumOfFieldA*sumOfFieldB)
-------------------------------------------------------------------
A    | 370         | 4.4         | 1628
B    | 200         | 1.5         | 300

名为 OutputRecord 的不同 POJO 将代表组合记录的每一行记录:

public class OutputRecord {
    private String name;
    private Integer sumOfFieldA;
    private BigDecimal sumOfFieldB;
    private BigDecimal fieldC;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSumOfFieldA() {
        return sumOfFieldA;
    }

    public void setSumOfFieldA(Integer sumOfFieldA) {
        this.sumOfFieldA = sumOfFieldA;
    }

    public BigDecimal getSumOfFieldB() {
        return sumOfFieldB;
    }

    public void setSumOfFieldB(BigDecimal sumOfFieldB) {
        this.sumOfFieldB = sumOfFieldB;
    }

    public BigDecimal getFieldC() {
        return fieldC;
    }

    public void setFieldC(BigDecimal fieldC) {
        this.fieldC = fieldC;
    }
}

将 InputRecords 列表转换为 OutputRecords 列表有哪些好的方法/解决方案?

我正在查看以下链接是否会有所帮助,但我在尝试将 fieldAfieldB 的收集器放在一起以形成 fieldC 的新收集器时遇到了困难: Java 8 Stream: groupingBy with multiple Collectors

Collector<InputRecord, ?, Integer> fieldACollector = Collectors.summingInt(InputRecord::getFieldA);
Collector<InputRecord, ?, BigDecimal> fieldBCollector = Collectors.reducing(BigDecimal.ZERO, InputRecord::getFieldB, BigDecimal::add);

List<Collector<InputRecord, ?, ?>> collectors = Arrays.asList(fieldACollector, fieldBCollector); // need a fieldCCollector object in the list

collectors 对象随后将用于创建 complexCollector 对象(根据 Tagir Valeev 在上述链接中接受的答案)。

【问题讨论】:

  • 既然可以即时计算,为什么还需要fieldC
  • 您能否提供有关您的 POJO 的更多信息?它是可变的吗?它有吸气剂吗?构造函数是什么样的?
  • 谢谢我添加了更多信息。 POJO 可以是可变的
  • 感谢 Holger,我已经添加了实际问题 :)

标签: java java-8 java-stream


【解决方案1】:

对我来说,最简洁的方法是为此构建一个自定义收集器。这里有多行代码,但是你可以把它隐藏在一个方法下,所以你的最终操作是这样的:

Collection<OutputRecord> output = List.of(first, second, thrid, fourth)
            .stream()
            .parallel()
            .collect(toOutputRecords());

而实际的toOutputRecords 是:

 private static Collector<InputRecord, ?, Collection<OutputRecord>> toOutputRecords() {
    class Acc {

        Map<String, OutputRecord> map = new HashMap<>();

        void add(InputRecord elem) {
            String value = elem.getName();
            // constructor without fieldC since you compute it at the end
            OutputRecord record = new OutputRecord(value, elem.getFieldA(), elem.getFieldB());
            mergeIntoMap(map, value, record);
        }

        Acc merge(Acc right) {
            Map<String, OutputRecord> leftMap = map;
            Map<String, OutputRecord> rightMap = right.map;

            for (Entry<String, OutputRecord> entry : rightMap.entrySet()) {
                mergeIntoMap(leftMap, entry.getKey(), entry.getValue());
            }
            return this;
        }

        private void mergeIntoMap(Map<String, OutputRecord> map, String value, OutputRecord record) {

            map.merge(value, record, (left, right) -> {
                left.setSumOfFieldA(left.getSumOfFieldA() + right.getSumOfFieldA());
                left.setSumOfFieldB(left.getSumOfFieldB().add(right.getSumOfFieldB()));

                return left;
            });
        }

        public Collection<OutputRecord> finisher() {
            for (Entry<String, OutputRecord> e : map.entrySet()) {
                OutputRecord output = e.getValue();
                output.setFieldC(output.getSumOfFieldB().multiply(BigDecimal.valueOf(output.getSumOfFieldA())));
            }
            return map.values();
        }

    }
    return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finisher);
}

【讨论】:

    【解决方案2】:

    您可以使用 Stream.reduce(..) 将两条记录转换为一条记录。它创建了一堆需要被 JVM 进行垃圾回收的临时对象。

    Collection<InputRecord> input = Arrays.asList(
            new InputRecord("A", 100, new BigDecimal(1.1)),
            new InputRecord("A", 150, new BigDecimal(2.0)),
            new InputRecord("B", 200, new BigDecimal(1.5)),
            new InputRecord("A", 120, new BigDecimal(1.3)));
    
    Collection<OutputRecord> output = input.stream()
            // group records for particular Name into a List
            .collect(Collectors.groupingBy(InputRecord::getName))
            .values().stream()
            // Reduce every List to a single records, performing summing
            .map(records -> records.stream()
                    .reduce((a, b) ->
                            new InputRecord(a.getName(),
                                    a.getFieldA() + b.getFieldA(),
                                    a.getFieldB().add(b.getFieldB()))))
            .filter(Optional::isPresent)
            .map(Optional::get)
            // Finally transform the InputRecord to OutputRecord
            .map(record -> new OutputRecord(record.getName(),
                    record.getFieldA(),
                    record.getFieldB(),
                    record.getFieldB().multiply(new BigDecimal(record.getFieldA()))))
            .collect(Collectors.toList());
    

    【讨论】:

    • 你可以在这里使用身份InputRecord(0, BigDecimla.ZERO) 而不是filter(Optional::isPresent).map(Optional::get),这里也建议使用可变收集器,因为它创建的对象更少。为了让这更漂亮,您可以再创建两个方法:InputRecord join(InputRecord left, InputRecord right) ... 和一个OutputRecord transform (InputRecord in) 形式的方法。因此,这条管道将变得更短且更具可读性。还是加一
    【解决方案3】:

    您可以使用组合和聚合函数从 InputRecords 列表生成 OutputRecords 列表。

    Map<String, OutputRecord> result = inputRecords.stream().collect(() -> new HashMap<>(),
                    (HashMap<String, OutputRecord> map, InputRecord inObj) -> {
                        OutputRecord out = map.get(inObj.getName());
                        if (out == null) {
                            out = new OutputRecord();
                            out.setName(inObj.getName());
                            out.setSumOfFieldA(inObj.getFieldA());
                            out.setSumOfFieldB(inObj.getFieldB());
                        } else {
    
                            Integer s = out.getSumOfFieldA();
                            out.setSumOfFieldA(s + inObj.getFieldA());
                            BigDecimal bd = out.getSumOfFieldB();
                            out.setSumOfFieldB(bd.add(inObj.getFieldB()));
                        }
                        out.setFieldC(out.getSumOfFieldB().multiply(new BigDecimal(out.getSumOfFieldA())));
                        map.put(out.getName(), out);
    
                    }, (HashMap<String, OutputRecord> out1, HashMap<String, OutputRecord> out2) -> {
                        out1.putAll(out2);
                    });
    
            System.out.println(result);
    

    【讨论】:

    【解决方案4】:

    与其定义自定义的收集器(我认为它复杂且难以维护),我认为组合多个收集器的通用实用方法会好得多。例如:

    public static <T, A1, A2, R1, R2> Collector<T, Tuple2<A1, A2>, Tuple2<R1, R2>> combine(final Collector<? super T, A1, R1> collector1,
            final Collector<? super T, A2, R2> collector2) {
     ...
    }
    

    使用 combine 方法,解决方案将是:

    Collector<InputRecord, ?, Integer> fieldACollector = MoreCollectors.summingInt(InputRecord::getFieldA);
    Collector<InputRecord, ?, BigDecimal> fieldBCollector = MoreCollectors.reducing(BigDecimal.ZERO, InputRecord::getFieldB, BigDecimal::add);
    
    inputRecords.stream().collect(MoreCollectors.groupingBy(InputRecord::getName, 
                                MoreCollectors.combine(fieldACollector, fieldBCollector)))
            .entrySet().stream()
            .map(e -> new OutputRecord(e.getKey(), e.getValue()._1, e.getValue()._2))
            .collect(Collectors.toList());
    

    这是AbacusUtilcombine 的示例实现

    StreamEx.of(inputRecords)
            .groupBy(InputRecord::getName, MoreCollectors.combine(fieldACollector, fieldBCollector))
            .map(e -> new OutputRecord(e.getKey(), e.getValue()._1, e.getValue()._2)).toList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 2014-06-11
      • 2017-04-19
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多