【发布时间】:2018-03-03 13:25:17
【问题描述】:
我有一个包含以下列标题的行的文件:
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() 运算符将返回一个新流,我如何获得(并因此求和)县的人口值?
【问题讨论】:
-
这段代码还能编译吗?
counties是一个 List? -
你的意思是
Map<String,Long> counties = txcArray.stream() .collect(Collectors.groupingBy(txc -> txc.getCounty(), Collectors.counting()));?
标签: java lambda stream java-stream