[英]Building a location hierarchy of counts
我有以下位置層次結構:
public class Location {
public Location parentLocation;
public String name;
public int id;
}
List<Location> listOfCities; // This list strictly contains all "city" level locations like Chicago, Atlanta etc.
讓我們假設parentLocation只能是一個國家,而一個國家的parentLocation是null。 即。 如果我有芝加哥的位置,芝加哥位置對象的parentLocation將是USA,並且鏈將終止於那里,因為USA位置parentLocation = null。 我有一個城市級別的位置對象列表,我想得到以下計數:
USA (20)
- Chicago (12)
- New York (1)
- Oregon (5)
- Atlanta (2)
Mexico (1)
- Puebla (1)
在Java8中是否有一種方便的方法來獲取一個jsonable對象,該對象將代表我在上面給出的城市位置列表中描述的計數層次結構? 我的嘗試:
// Get counts of all cities in listOfCities (ie. Chicago -> 12)
Map<String, Integer> cityCounts = listOfCities.stream()
.map(Location::name)
.collect(Collectors.toMap(city -> city, city -> 1, Integer::sum));
我不確定如何通過parentLocation獲取“累計”計數,並將所有內容整合到一個干凈的響應對象中,該對象可以像上面漂亮的方式一樣走路。
您可以生成Map<String, Map<String, Long>>
,在外部地圖中包含國家/地區名稱,在內部地圖中包含城市名稱/計數。
import static java.util.stream.Collectors.*;
Map<String,Map<String,Long>> cityCountsByCountry = listOfCities
.stream()
.collect(groupingBy(city -> city.parentLocation.name,
groupingBy(city -> city.name,
counting())));
這會產生類似於這個JSON的結構:
{
"USA": {
"Chicago": 12,
"New York": 1,
"Oregon": 5,
"Atlanta": 2
},
"Mexico": {
"Puebla": 1
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.