【问题标题】:Key-value collection with convenient notation具有方便符号的键值集合
【发布时间】:2011-08-14 15:10:22
【问题描述】:

我正在寻找一个类似于 Map 的集合,它允许我以 PHP/Python/JavaScript 的方式创建新对象:

var foo = new Foo({'foo': 'bar'})

我在 Java 中最接近的是 HashMap:

Map<String, String> parameters = new HashMap<String, String>();
parameters.put("test", "one two");
parameters.put("foo", "bar");

这对于我的目的来说太冗长了。我想以更简单的方式写下和处理键值对。

我欢迎任何建议 - 创建自己的集合类型,为 Map 对象创建自己的工厂等。我只是想减少创建此类集合所需的字符数。

【问题讨论】:

标签: java collections map


【解决方案1】:

我见过的一种方法是,在坚持使用基本 JDK 时,只使用匿名初始化器:

Map<String, String> parameters = new HashMap<String, String>() {{
  put("test", "one two");
  put("foo", "bar");
}};

你也可以看看 Guava ImmutableMap builder:http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableMap.Builder.html

如果你想走得更远一点,你可以为 JSON 之类的东西(或者只是 JSON 本身和一个 JSON 库)编写一个解析器,然后将 Map 写成一个字符串。

【讨论】:

  • 谢谢!我会使用双括号技巧,但 JSON 建议也不错。
【解决方案2】:

你有(不是很知名的)double brace initialization trick

Map<String, String> Map = new HashMap<String, String>() {{
      put("test", "one two");
      put("foo", "bar");
}};

使用 java 7 钻石运算符,这更加简洁,请参阅:

Map<String, String> Map = new HashMap<>() {{
      put("test", "one two");
      put("foo", "bar");
}};
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
相关资源
最近更新 更多