以下是一个示例,说明如何获得此统计信息:
// you need to preload this
Map<String,Integer> populationMap = new HashMap<>();
populationMap.put("95103", 100);
populationMap.put("95123", 200);
populationMap.put("93143", 300);
Map<String,Integer> crimeMap = new HashMap<>();
// update the counter with every event
crimeMap.merge("95103", 1, Integer::sum);
// update the counter with every event
crimeMap.merge("95103", 1, Integer::sum);
// update the counter with every event
crimeMap.merge("95123", 1, Integer::sum);
// to get the final stats
Map<String, Float> collect = populationMap.entrySet().stream()
.map(populationMapEntry -> {
String zipCode = populationMapEntry.getKey();
Integer populationInZipCode = populationMapEntry.getValue();
Integer crimeInZipCode = crimeMap.getOrDefault(zipCode, 0);
Float rate = crimeInZipCode.floatValue() / populationInZipCode.floatValue();
return new AbstractMap.SimpleEntry<String, Float>(zipCode, rate);
})
.collect(Collectors.toMap(
entry -> entry.getKey(),
entry -> entry.getValue()));
System.out.println(collect);
// {95123=0.005, 95103=0.02, 93143=0.0}
为了更具表现力,我使用了更多的变量。