HashMap<字符串 ,布尔值>将所有键复制到 HashMap并将值初始化为零

发布于 2024-10-01 18:30:32 字数 266 浏览 0 评论 0原文

最好的办法是什么?

只需循环并输入键和零,或者是否有另一种更优雅或现有的库方法。我也在使用 Google 的 guava java 库,它是否有任何有用的功能?

想检查是否有类似于列表复制方法或Map的putAll 方法,但仅用于键。

What is the best way ?

Just looping through and putting the key and zero, or is there another more elegant or existing library method. I am also using Google's guava java library if that has any useful functionality ?

Wanted to check if there was anything similar to the copy method for lists, or Map's putAll method, but just for keys.

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

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

发布评论

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

评论(3

北座城市 2024-10-08 18:30:32

不要认为这里有太多需要任何花哨的东西:

Map<String, Boolean> map = ...;
Map<String, Integer> newMap = Maps.newHashMapWithExpectedSize(map.size());
for (String key : map.keySet()) {
  newMap.put(key, 0);
}

如果你确实想要 Guava 的一些花哨的东西,有这个选项:

Map<String, Integer> newMap = Maps.newHashMap(
    Maps.transformValues(map, Functions.constant(0)));

// 1-liner with static imports!
Map<String, Integer> newMap = newHashMap(transformValues(map, constant(0)));

Don't think there's much need for anything fancy here:

Map<String, Boolean> map = ...;
Map<String, Integer> newMap = Maps.newHashMapWithExpectedSize(map.size());
for (String key : map.keySet()) {
  newMap.put(key, 0);
}

If you do want something fancy with Guava, there is this option:

Map<String, Integer> newMap = Maps.newHashMap(
    Maps.transformValues(map, Functions.constant(0)));

// 1-liner with static imports!
Map<String, Integer> newMap = newHashMap(transformValues(map, constant(0)));
向日葵 2024-10-08 18:30:32

循环非常简单(而且并不不优雅)。迭代原始 Map 的键,并将其放入新副本中,且值为零。

Set<String> keys = original.keySet();
Map<String, Integer> copy = new HashMap<String, Integer>();
for(String key : keys) {
    copy.put(key, 0);
}

希望有帮助。

Looping is pretty easy (and not inelegant). Iterate over the keys of the original Map and put it in them in the new copy with a value of zero.

Set<String> keys = original.keySet();
Map<String, Integer> copy = new HashMap<String, Integer>();
for(String key : keys) {
    copy.put(key, 0);
}

Hope that helps.

捶死心动 2024-10-08 18:30:32
final Integer ZERO = 0;

for(String s : input.keySet()){
   output.put(s, ZERO);
}
final Integer ZERO = 0;

for(String s : input.keySet()){
   output.put(s, ZERO);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文