不幸的是,集合文字在 Java 7(和 Java 8)中是 proposal for Project Coin,但 它从未进入最终产品,也就是说它不是Java的特性。
命题是这样的
Here’s how it would look with map literals:
final Map<Integer, String> platonicSolids = {
4 : "tetrahedron",
6 : "cube",
8 : "octahedron",
12 : "dodecahedron",
20 : "icosahedron"
};
Here is the empty map literal, which has a slightly irregular syntax to make
it differ from the empty set:
Map<String, Integer> noJokeHere = { : };
但它从未发生过,所以很遗憾,这不起作用。因此,除非您编写自己的魔法构建器或像on this site of Per-Åke Minborg 这样的花哨的 lambda,否则您只能靠自己。不过,该站点的以下内容应该可以工作(在 Java 8 中)。
//copy paste from linked site
Map<Integer, String> map = Stream.of(
new SimpleEntry<>(0, "zero"),
new SimpleEntry<>(1, "one"),
//...
new SimpleEntry<>(11, "eleven"),
new SimpleEntry<>(12, "twelve"))
.collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()));
还有简化版,同样来自site:
//copy paste from linked site
public static <K, V> Map.Entry<K, V> entry(K key, V value) {
return new AbstractMap.SimpleEntry<>(key, value);
}
public static <K, U> Collector<Map.Entry<K, U>, ?, Map<K, U>> entriesToMap() {
return Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue());
}
Map<Integer, String> map = Stream.of(
entry(0, "zero"),
//...
entry(12, "twelve"))
.collect(entriesToMap());
由于these points,没有引入集合字面量:
此功能的“简单”版本(仅限集合、列表、地图)不是
非常令人满意或受欢迎;此功能的“可扩展”版本是
开放式、凌乱的,并且几乎可以保证会超出其设计
预算;
基于库的版本为我们提供了 1% 的 X% 的收益
成本,其中 X >> 1;
值类型即将到来,以及“此功能会是什么样子”
在具有值类型的世界中可能与在世界中完全不同
没有,暗示尝试做这项工作是有问题的
在值类型之前;
我们最好将我们的语言设计带宽集中在
解决更多基于图书馆的基础问题
版本(包括:更高效的可变参数、数组常量
常量池、不可变数组以及对缓存(和回收)的支持
在压力下)中间不可变的结果)。
By Brian Goetz from Oracle