How do I use collection literals in Java 7?

collections, java

Solution

Neither Java 7 nor Java 8 supports collection literals, as discussed in this question: Are Project Coin's collection enhancements going to be in JDK8?

You can use Google's Guava library if you need only immutable collections. `ImmutableList`, `ImmutableSet` and `ImmutableMap` have several overloaded factory methods or even builders that make creating collections easy:

List<Integer> list = ImmutableList.of(1, 1, 2, 3, 5, 8, 13, 21);
Set<String> set = ImmutableSet.of("foo", "bar", "baz", "batman");
Map<Integer, String> map = ImmutableMap.of(1, "one", 2, "two", 3, "three");

EDIT

Java 9 has added collection factory methods similar to those of Guava:

List.of(a, b, c);
Set.of(d, e, f, g);
Map.of(k1, v1, k2, v2)

Map.ofEntries(
    entry(k1, v1),
    entry(k2, v2),
    entry(k3, v3),
    // ...
    entry(kn, vn)
);

Problem

I've tried the following line: ``` Map<Character, Color> map={new Character('r'):Color.red,new Character('b'):Color.black}; ``` But Netbeans 7 rejects this, with the error message `'{' expected, ';' expected`. I've set the Source/Binary format as 'JDK 7'and the platform to 'JDK 1.7', is there anything else I need to do?

Original source

Related problems