Java Stream新手在这里。目前,我正在从[book]完成关于收集器的第6章(使用流收集数据)。
我的对象看起来像这样。
public class Report { private String movie; private int movieId; private int projections; private int tickets; private double income; }
想法是获得某种一般的摘要报告。基本上,
HashMap<String, Double>
它将具有三个键值对。
键1:
projections
-将代表每个报告的所有预测的总和。
键2:
tickets
-代表每个报告中所有票证的总和。
键3:
[income
-代表每份报告的所有收入之和。
现在,我实际上是通过创建名为MapCollector
的自定义收集器来进行分配的。
public class MapCollector implements Collector<Report, Map<String, Double>, Map<String, Double>>{ @SuppressWarnings("serial") @Override public Supplier<Map<String, Double>> supplier() { return () -> new HashMap<String, Double>() {{ put("projections", 0.0); put("tickets", 0.0); put("income", 0.0); }}; } @Override public BiConsumer<Map<String, Double>, Report> accumulator() { return (map, report) -> { map.put("projections", map.get("projections") + report.getProjections()); map.put("tickets", map.get("tickets") + report.getTickets()); map.put("income", map.get("income") + report.getIncome()); }; } @Override public BinaryOperator<Map<String, Double>> combiner() { // TODO Auto-generated method stub return null; } @Override public Function<Map<String, Double>, Map<String, Double>> finisher() { // TODO Auto-generated method stub return Function.identity(); } @Override public Set<Characteristics> characteristics() { // TODO Auto-generated method stub return Collections.unmodifiableSet(EnumSet.of( IDENTITY_FINISH, CONCURRENT)); } }
所以我得到的结果,看起来像这样:
HashMap<String, Double> result = (HashMap<String, Double>) reports.stream().collect(new MapCollector());
所以我的问题是为什么不创建新的Collector对象就以不同的方式执行此操作?也许以某种方式使用
groupingBy
或reduce
可以做到?还是任何其他(更好的)更具可读性的方式?
Java Stream新手在这里。目前,我正在完成本书有关收集器的第6章(使用流收集数据)。我的对象看起来像这样。公共类Report {private String ...
您实际上不需要为此目的使用自定义收集器。您只需要supplier
,accumulator
和combiner
。