I have a file with rows with the following column headers:
CITY_NAME COUNTY_NAME POPULATION
Atascocita Harris 65844
Austin Travis 931820
Baytown Harris 76335
...
I am using streams to attempt to generate an output similar to:
COUNTY_NAME CITIES_IN_COUNTY POPULATION_OF_COUNTY
Harris 2 142179
Travis 1 931820
...
So far I have been able to use streams to get a list of distinct county names (as these are repetitive), but now I am having issues with getting the count of cities in a distinct county and consequently the sum of the populations of cities in these counties. I have read the file into an ArrayList of type texasCitiesClass, and my code thus far looks like:
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;
}
At this point, I have a stream containing the names of unique counties. Since the sorted() operator will return a new stream, how can I obtain (and thus sum) the population values for the counties?