Java - 遍历包含列表的地图

2023-10-14Java开发问题
2

本文介绍了Java - 遍历包含列表的地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

第一次来这里,所以我希望这是有道理的!

First time here so I hope this makes sense!

我有一个 Map,其中包含一个字符串作为它的键,以及一个字符串列表作为它的值.我需要遍历地图中每个列表中包含的所有变量.

I have a Map which contains a String as it's Key, and a List of Strings as it's Value. I need to iterate over all vlaues contained within each List within the Map.

所以,首先我想获得有效的密钥:

So, first I want to get the Keys, which works:

Set<String> keys = theMap.keySet();

这将返回一个包含我所有密钥的集合.太好了:)

This returns me a Set containing all my Keys. Great :)

这是我卡住的地方 - 网络上的大多数信息似乎都假设我希望从 Key 返回的值是一个简单的 String 或 Integer,而不是另一个 Set,或者在这种情况下是一个列表.我尝试了 theMap.values() 但这不起作用,我尝试了一个 forloop/for:eachloop,但这些都没有成功.

This is where I've got stuck - most of the info on the web seems to assume that the values I'd want returned from the Key would be a simple String or Integer, not another Set, or in this case a List. I tried theMap.values() but that didn't work, and I tried a forloop / for:eachloop, and neither of those did the trick.

谢谢大家!

推荐答案

for(List<String> valueList : map.values()) {
  for(String value : valueList) {
    ...
  }
}

这才是真正的正常".方法来做到这一点.或者,如果您也需要密钥...

That's really the "normal" way to do it. Or, if you need the key as well...

for(Map.Entry<String, List<String>> entry : map.entrySet()) {
  String key = entry.getKey();
  for (String value : entry.getValue()) {
    ...
  }
}

也就是说,如果您可以选择,您可能会对 Guava 的 ListMultimap,这是一个很像 Map<K, List<V>>,但有更多的功能——包括 Collection<V>values() 的行为与您所要求的完全一样,扁平化";多重映射中的所有值到一个集合中.(披露:我为 Guava 做出了贡献.)

That said, if you have the option, you might be interested in Guava's ListMultimap, which is a lot like a Map<K, List<V>>, but has a lot more features -- including a Collection<V> values() that acts exactly like what you're asking for, "flattening" all the values in the multimap into one collection. (Disclosure: I contribute to Guava.)

这篇关于Java - 遍历包含列表的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13