DaedalusUsedPerl
DaedalusUsedPerl

Reputation: 772

How do I use collection literals in Java 7?

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?

Upvotes: 24

Views: 19337

Answers (3)

Natix
Natix

Reputation: 14247

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)
);

Upvotes: 52

Thomas
Thomas

Reputation: 88707

You need to define a concrete map implementation, optionally combined with double brace initialization:

Map<Character, Color> map = new HashMap<Character, Color>() {{ 
  put(new Character('r'), Color.red);
  put(new Character('b'), Color.black );
}};

Upvotes: 11

Seth
Seth

Reputation: 322

To expand a little on Thomas's answer... Map is an interface, and must be instantiated through one of the associated concrete implementations (HashMap, TreeMap, or LinkedHashMap). It is still good practice; however, to declare your reference variable as the interface implementation rather than the specific concrete, as it provides future flexibility.

Regarding the code snippet though, I think you do still need the Key-value pairs defined in the assignment side of the declaration. So, I would change:

Map<Character, Color> map = new HashMap<>() {{ 

to

Map<Character, Color> map = new HashMap<Character, Color>() {{ 

Upvotes: 0

Related Questions