英文:
Get String from List of Maps in Java 8
问题
我有:List<Map<String, String>> countries
,我能够通过以下方式获取我感兴趣的值:
String value = "";
for (int i = 0; i < countries.size(); i++) {
Map<String, String> map = countries.get(i);
if (map.containsValue(country)) {
value = map.get(COUNTRY_NAME);
}
}
return value;
所以一般来说 - 如果在地图中有我感兴趣的国家,那么我会获取键为COUNTRY_NAME的值。
如何将其转换为流呢?我尝试过以下方式:
for (Map<String, String> m : countries) {
description = String.valueOf(m.entrySet()
.stream()
.filter(map -> map.getValue().equals(country))
.findFirst());
}
但首先它无法正常工作,其次我仍然使用了for each循环。
英文:
I have: List<Map<String, String>> countries
and I was able to get value which I am interested in by this:
String value = "";
for (int i = 0; i < countries.size(); i++) {
Map<String, String> map = countries.get(i);
if (map.containsValue(country)) {
value = map.get(COUNTRY_NAME);
}
}
return value;
so in general - if in map is country which I am interested in then I take value where key is COUNTRY_NAME.
How can I translate it to streams? I tried this way:
for (Map<String, String> m : countries) {
description = String.valueOf(m.entrySet()
.stream()
.filter(map -> map.getValue().equals(country))
.findFirst());
}
but first it doesn't work, second I still used for each loop.
答案1
得分: 3
你需要过滤地图,如果它包含值,则使用.map()
转换数据,然后在.findFirst()
之后使用.orElse()
返回默认值(如果找不到)。
String value = countries.stream()
.filter(m -> m.containsValue(country))
.map(m -> m.get(COUNTRY_NAME))
.findFirst()
.orElse("");
英文:
You need to filter map if it's containsValue
then transform your data using .map()
then after .findFirst()
use .orElse()
to return default value if not found.
String value = countries.stream()
.filter(m -> m.containsValue(country))
.map(m -> m.get(COUNTRY_NAME))
.findFirst()
.orElse("");
答案2
得分: 1
我认为你可以尝试:
Stream.of(countries).reduce(Stream::concat)
.filter(map -> map.getValue().equals(country))
.findFirst();
这个页面 似乎展示了一些可以帮助你的内容。
英文:
I think you can try:
Stream.of(countries).reduce(Stream::concat)
.filter(map -> map.getValue().equals(country))
.findFirst();
That page seems to show things that can help you.
答案3
得分: 1
请查看以下内容:
Optional<Map<String, String>> countryOpt = countries
.stream()
.filter(c -> c.containsValue(COUNTRY_NAME))
.findAny();
if (countryOpt.isPresent()) {
value = countryOpt.get().get(COUNTRY_NAME);
}
英文:
Check this:
Optional<Map<String, String>> countryOpt = countries
.stream()
.filter(c -> c.containsValue(COUNTRY_NAME))
.findAny();
if (countryOpt.isPresent()) {
value = countryOpt.get().get(COUNTRY_NAME);
}
答案4
得分: 1
Optional<String> countryOptional = countries.stream()
.filter(kvp -> kvp.containsKey(COUNTRY_NAME))
.map(kvp -> kvp.get(COUNTRY_NAME))
.findFirst();
英文:
Optional<String> countryOptional = countries.stream()
.filter(kvp -> kvp.containsKey(COUNTRY_NAME))
.map(kvp -> kvp.get(COUNTRY_NAME))
.findFirst();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论