有没有更有效的方法使用ArrayList中的计数器来创建HashMap?

Log*_*nam 1 java sorting counter arraylist hashmap

我有一个方法,让我来创建一个HashMapArrayList通过获取AirbnbListing对象,然后在附近的名称与任何键进行比较HashMap.如果它还没有在hashmap中,我将它添加一个从1开始的计数器,如果它已经存在,我增加计数器.

这里有一个更有效的方法是我的代码:

    public HashMap<String, Integer> sortHousesInNbrhood(ArrayList<AirbnbListing> priceRangeListing) {
    HashMap<String, Integer> housesInNbrhood = new HashMap<>();
    for (AirbnbListing listing : priceRangeListing) {
        if (housesInNbrhood.isEmpty()) {
            housesInNbrhood.put(listing.getNeighbourhood(), 1); 
        } else if (housesInNbrhood.containsKey(listing.getNeighbourhood())) {
            housesInNbrhood.replace(listing.getNeighbourhood(), housesInNbrhood.get(listing.getNeighbourhood()) + 1);
        } else {
            housesInNbrhood.put(listing.getNeighbourhood(),1); 
        }
    }

    return housesInNbrhood;
}
Run Code Online (Sandbox Code Playgroud)

Ous*_* D. 8

使用groupingBy收集器counting作为下游收集器:

priceRangeListing.stream()
                 .collect(groupingBy(AirbnbListing::getNeighbourhood, counting()));
Run Code Online (Sandbox Code Playgroud)

注意,上面会产生一个,Map<String, Long>但如果你真的想要Map<String, Integer>那么使用summingInt收集器作为下游:

priceRangeListing.stream()
       .collect(groupingBy(AirbnbListing::getNeighbourhood, summingInt(e -> 1)));
Run Code Online (Sandbox Code Playgroud)