使用循环从 HashSet 值创建 HashMap

发布于 2025-01-09 00:23:25 字数 519 浏览 4 评论 0原文

我正在尝试从 HashSet 的值创建 HashMap (它本身作为值存储在 HashMap 中)。

我不确定是否要迭代或使用 for 循环。

示例:

newMap = new HashMap<String, HashSet<String>>();
HashSet<String> boxing = new HashSet<String>();
        
        newMap.put("fighting", boxing);
        boxing.add("jab");
        boxing.add("hook");
        boxing.add("uppercut");

现在我需要迭代或循环,以便“装箱”HashSet 中的每个值创建一个新的 HashMap,并将该值作为新映射的键。

因此 newMap1 将以 'jab' 作为键,newMap2 将以 'hook' 作为键,依此类推。

任何帮助表示赞赏。

I'm trying to create a HashMap from values of a HashSet (which itself is stored as values in a HashMap).

I'm not sure whether to Iterate or use a for loop.

Example:

newMap = new HashMap<String, HashSet<String>>();
HashSet<String> boxing = new HashSet<String>();
        
        newMap.put("fighting", boxing);
        boxing.add("jab");
        boxing.add("hook");
        boxing.add("uppercut");

Now I need to iterate or loop through so that each value in the 'boxing' HashSet creates a new HashMap with the value as the key for the new map.

So newMap1 would have 'jab' as the key, newMap2 would have 'hook' as the key and so on.

Any help is appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

韶华倾负 2025-01-16 00:23:25

从 Java 9 开始你可以这样做:

Map<String, Set<String>> newMap = Map.of("fighting", Set.of("jab","hook","uppercut"));

Since Java 9 you can do this:

Map<String, Set<String>> newMap = Map.of("fighting", Set.of("jab","hook","uppercut"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文