【发布时间】:2014-10-31 13:23:10
【问题描述】:
我正在处理人口统计数据。我有一个州不同县的记录集合(每个县有几条记录),我想按县汇总。
我已经实现了以下消费者:
public class CountyPopulation implements java.util.function.Consumer<Population>
{
private String countyId ;
private List<Demographic> demographics ;
public CountyPopulation()
{
demographics = new ArrayList<Demographic>() ;
}
public List<Demographic> getDemographics()
{
return demographics ;
}
public void accept(Population pop)
{
if ( countyId == null )
{
countyId = pop.getCtyId() ;
}
demographics.add( pop.getDemographic() ) ;
}
public void combine(CountyPopulation other)
{
demographics.addAll( other.getDemographics() ) ;
}
}
此 CountyPopulation 用于使用以下代码(其中“089”是县标识符)聚合有关特定县的数据:
CountyPopulation ctyPop = populations
.stream()
.filter( e -> "089".equals( e.getCtyId() ) )
.collect(CountyPopulation::new,
CountyPopulation::accept,
CountyPopulation::combine) ;
现在,我想在使用我的聚合器之前删除“过滤器”并按县对记录进行分组。
根据您的第一个答案,我知道这可以通过以下方式使用静态函数 Collector.of 完成:
Map<String,CountyPopulation> pop = populations
.stream()
.collect(
Collectors.groupingBy(Population::getCtyId,
Collector.of( CountyPopulation::new,
CountyPopulation::accept,
(a,b)->{a.combine(b); return a;} ))) ;
但是,此代码不起作用,因为 Collector.of() 的签名与 collect() 不同。 我怀疑该解决方案涉及修改类 CountyPopulation 以便它实现 java.util.function.BiConsumer 而不是 java.util.function.Consumer 但我这样做的尝试没有奏效,我不清楚为什么。
【问题讨论】: