我有行的文件,以下列标题:的Java 8流:在总和值的不同键
CITY_NAME COUNTY_NAME POPULATION
Atascocita Harris 65844
Austin Travis 931820
Baytown Harris 76335
...
我使用流以尝试产生类似的输出:
COUNTY_NAME CITIES_IN_COUNTY POPULATION_OF_COUNTY
Harris 2 142179
Travis 1 931820
...
到目前为止,我已经能够使用流获取不同县名的列表(因为这些是重复的),但是现在我遇到了在一个不同的县获得城市数量的问题,并因此导致了人口总数这些县的城市。我已阅读文件到类型texasCitiesClass的ArrayList,和我的代码到目前为止看起来像:
public static void main(String[] args) throws FileNotFoundException, IOException {
PrintStream output = new PrintStream(new File("output.txt"));
ArrayList<texasCitiesClass> txcArray = new ArrayList<texasCitiesClass>();
initTheArray(txcArray); // this method will read the input file and populate an arraylist
System.setOut(output);
List<String> counties;
counties = txcArray.stream()
.filter(distinctByKey(txc -> txc.getCounty())) // grab distinct county names
.distinct() // redundant?
.sorted((txc1, txc2) -> txc1.getCounty().compareTo(txc2.getCounty())); // sort alphabetically
}
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, String> seen = new ConcurrentHashMap<>();
return t -> seen.put(keyExtractor.apply(t), "") == null;
}
在这一点上,我有一个包含唯一的县名称的流。由于sorted()运算符将返回一个新的流,因此我如何获得(并因此求和)各个县的人口值?
这段代码是否可以编译? '县'是列表? –
nullpointer
你的意思是'Map counties = txcArray.stream().collect(Collectors.groupingBy(txc - > txc.getCounty(),Collectors.counting()));'? –
Holger