Java流:groupingBy和flatMapping键 [英] Java streams: groupingBy and flatMapping keys
问题描述
说我有一个国家对象列表,其中包含该国家使用的语言列表,例如:
Say I have a list of country objects that contain lists of languages spoken in that country, like so:
class Country {
List<String> languages;
}
我想以以下格式创建地图: Map< String,List< Country>>
,以便每种语言都映射到Country对象的列表.例如:
I would like to create a map in the following format:
Map<String, List<Country>>
, such that a each language maps to a list of Country objects. E.g.:
"French" -> [Country:France, Country:Canada],
"English" -> [Country:UK, Country:US]
这里的性能是一个问题,所以我想避免多次迭代和查找.我已经尝试过使用 groupingBy
,但是我该如何 flatMap
键集?
Performance is an issue here, so I would like to avoid multiple iterations and lookups. I have tried using groupingBy
, but how do I flatMap
the keyset?
例如,这将导致 Map< List< String>,List< Country>>
:
countries.stream()
.collect(Collectors.groupingBy(country -> country.getLanguages(), toList()));
推荐答案
由于您似乎关心性能,因此请勿将流用于此简单任务:
Since you seem to care about performance, don't use streams for this simple task:
Map<String, List<Country>> countriesByLanguage = new HashMap<>();
for (Country country : countries) {
for (String language : country.getLanguages()) {
countriesByLanguage.computeIfAbsent(language, k -> new ArrayList<>())
.add(country);
}
}
这篇关于Java流:groupingBy和flatMapping键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!