C# 到 Java - 字典?

发布于 2024-11-27 09:40:59 字数 286 浏览 1 评论 0原文

在Java中是否可以制作一个包含已在其中声明的项目的字典?就像下面的 C# 代码一样:

   Dictionary<string, int> d = new Dictionary<string, int>()
    {
        {"cat", 2},
        {"dog", 1},
        {"llama", 0},
        {"iguana", -1}
    };

我该如何执行此操作以及我使用什么类型?我读到字典已经过时了。

Is it possible in Java to make a Dictionary with the items already declared inside it? Just like the below C# code:

   Dictionary<string, int> d = new Dictionary<string, int>()
    {
        {"cat", 2},
        {"dog", 1},
        {"llama", 0},
        {"iguana", -1}
    };

How do I do this and what type do I use? I've read that Dictionary is obsolete.

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

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

发布评论

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

评论(5

橪书 2024-12-04 09:40:59

这将执行您想要的操作:

Map<String,Integer> map = new HashMap<String, Integer>(){{
    put("cat", 2);
    put("dog", 1);
    put("llama", 0);
    put("iguana", -1);
}};

此语句创建 HashMap 的匿名子类,其中与父类的唯一区别是在实例创建期间添加了 4 个条目。这是 Java 世界中相当常见的习惯用法(尽管有些人认为它有争议,因为它创建了一个新的类定义)。

由于这个争议,从 Java 9 开始,出现了一种可以方便地构建映射的新习惯用法:静态 Map.of 方法

使用 Java 9 或更高版本,您可以按如下方式创建所需的地图:

Map<String, Integer> map = Map.of(
    "cat", 2,
    "dog", 1,
    "llama", 0,
    "iguana", -1
);

对于较大的地图,此 替代语法可能不太容易出错:(

Map<String, Integer> map = Map.ofEntries(
    Map.entry("cat", 2),
    Map.entry("dog", 1),
    Map.entry("llama", 0),
    Map.entry("iguana", -1)
);

如果 Map.entry 是静态导入而不是被引用,这尤其好明确)。

除了仅适用于 Java 9+ 之外,这些新方法与前一种方法并不完全相同:

  • 它们不允许您指定使用什么 Map 实现
  • 它们只创建不可变的映射
  • 它们不创建 Map 的匿名子类

但是,这些差异对于许多用例来说并不重要,这使得这成为新版本 Java 的良好默认方法。

This will do what you want:

Map<String,Integer> map = new HashMap<String, Integer>(){{
    put("cat", 2);
    put("dog", 1);
    put("llama", 0);
    put("iguana", -1);
}};

This statement creates an anonymous subclass of HashMap, where the only difference from the parent class is that the 4 entries are added during instance creation. It's a fairly common idiom in the Java world (although some find it controversial because it creates a new class definition).

Because of this controversy, as of Java 9 there is a new idiom for conveniently constructing maps: the family of static Map.of methods.

With Java 9 or higher you can create the map you need as follows:

Map<String, Integer> map = Map.of(
    "cat", 2,
    "dog", 1,
    "llama", 0,
    "iguana", -1
);

With larger maps, this alternative syntax may be less error-prone:

Map<String, Integer> map = Map.ofEntries(
    Map.entry("cat", 2),
    Map.entry("dog", 1),
    Map.entry("llama", 0),
    Map.entry("iguana", -1)
);

(This is especially nice if Map.entry is statically imported instead of being referenced explicitly).

Besides only working with Java 9+, these new approaches are not quite equivalent to the previous one:

  • They don't allow you to specify what Map implementation is used
  • They only create immutable maps
  • They don't create an anonymous subclass of Map

However, these differences shouldn't matter for many use cases, making this a good default approach for newer versions of Java.

余罪 2024-12-04 09:40:59
Map<String,Integer> map = new HashMap<String, Integer>(){{
put("cat", 2);
put("dog", 1);
put("llama", 0);
put("iguana", -1);
}};
Map<String,Integer> map = new HashMap<String, Integer>(){{
put("cat", 2);
put("dog", 1);
put("llama", 0);
put("iguana", -1);
}};
淡淡绿茶香 2024-12-04 09:40:59

硬着头皮打出地图名称!

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("cat", 2);
    map.put("dog", 1);
    map.put("llama", 0);
    map.put("iguana", -1);

您也可以执行类似的操作,这可能会节省一些输入长列表的操作:

    Object[][] values = {
        {"cat", 2},
        {"dog", 1},
        {"llama", 0},
        {"iguana", -1}
    };

    for (Object[] o : values) {
        map.put((String) o[0], (Integer) o[1]);
    }

Bite the bullet and type out the map name!

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("cat", 2);
    map.put("dog", 1);
    map.put("llama", 0);
    map.put("iguana", -1);

You could also do something like this, which might save some typing with a long list:

    Object[][] values = {
        {"cat", 2},
        {"dog", 1},
        {"llama", 0},
        {"iguana", -1}
    };

    for (Object[] o : values) {
        map.put((String) o[0], (Integer) o[1]);
    }
情泪▽动烟 2024-12-04 09:40:59

如果您使用 Guava 库,则可以使用其 ImmutableMap 类,或者单独使用(示例 1 和 2),或作为 HashMap 的初始化器(示例 3 和 4):

Map<String, Integer> map1 = ImmutableMap.<String, Integer> builder()
    .put("cat", 2)
    .put("dog", 1)
    .put("llama", 0)
    .put("iguana", -1)
    .build();
Map<String, Integer> map2 = ImmutableMap.of(
    "cat", 2,
    "dog", 1,
    "llama", 0,
    "iguana", -1
);
Map<String, Integer> map3 = Maps.newHashMap(
    ImmutableMap.<String, Integer> builder()
    .put("cat", 2)
    .put("dog", 1)
    .put("llama", 0)
    .put("iguana", -1)
    .build()
);
Map<String, Integer> map4 = Maps.newHashMap( ImmutableMap.of(
    "cat", 2,
    "dog", 1,
    "llama", 0,
    "iguana", -1)
);

If you use the Guava library, you can use its ImmutableMap class, either by itself (examples 1 and 2), or as an initializer for a HashMap (examples 3 and 4):

Map<String, Integer> map1 = ImmutableMap.<String, Integer> builder()
    .put("cat", 2)
    .put("dog", 1)
    .put("llama", 0)
    .put("iguana", -1)
    .build();
Map<String, Integer> map2 = ImmutableMap.of(
    "cat", 2,
    "dog", 1,
    "llama", 0,
    "iguana", -1
);
Map<String, Integer> map3 = Maps.newHashMap(
    ImmutableMap.<String, Integer> builder()
    .put("cat", 2)
    .put("dog", 1)
    .put("llama", 0)
    .put("iguana", -1)
    .build()
);
Map<String, Integer> map4 = Maps.newHashMap( ImmutableMap.of(
    "cat", 2,
    "dog", 1,
    "llama", 0,
    "iguana", -1)
);
心奴独伤 2024-12-04 09:40:59

Java7 几乎引入了允许这样的语法的“集合文字”。他们可能会尝试将其推入 Java8。我不知道这些人出了什么问题。

这可以通过某种包装 API 轻松实现,

Map<String,Integer> map = Maps.<String,Integer>empty()
    .put("cat", 2).put("dog",1)....; 

还不错。我更喜欢这样的东西,

map("cat", "dog", ... )
.to(  1,     2,   ... );

这种东西必须由不同的人实现,不幸的是标准API不包含这样的东西。

Java7 almost introduced "collection literals" that would allow syntax like that. They'll probably try to shove it in Java8. I have no idea what is wrong with these people.

This can be easily achieved by some kind of wrapper API

Map<String,Integer> map = Maps.<String,Integer>empty()
    .put("cat", 2).put("dog",1)....; 

Not too bad. I would prefer something like

map("cat", "dog", ... )
.to(  1,     2,   ... );

This kind of thing must have been implemented by various people, unfortunately the standard API doesn't inculde such things.

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