【发布时间】:2016-11-02 14:42:42
【问题描述】:
我有以下位置层次结构:
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 为空。 IE。如果我有芝加哥的位置,则芝加哥位置对象的 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 获取“汇总”计数,并将所有内容放入一个干净的响应对象中,该对象可以以上面漂亮打印的方式行走。
【问题讨论】:
-
芝加哥有 12 个,因为还有 12 个其他城市是芝加哥的父级城市吗?
listOfCities是所有地点、父母和非父母的List<Location>吗? -
@4castle Chicago 有 12 个,因为有 12 个城市的 String name = "Chicago"。 listOfCities 是一个 List
所有非父母(即城市级别的 Location 对象)。城市之外没有位置级别,并且城市的 parentLocation = country。 -
谢谢,这一切都清楚了。
USA是否会作为键包含在输出Map中? -
看来您是本末倒置。首先弄清楚你要构建什么结构,然后让我们看看 Java 8 是否可以提供帮助
-
也许你想要
Map<String, Map<String, Integer>>?外层地图是国家,内层地图是城市及其数量。请edit您的问题与您想要的输出结构。