Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use collection literals in Java 7?

Tags:

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?

like image 969
DaedalusUsedPerl Avatar asked May 22 '12 16:05

DaedalusUsedPerl


People also ask

What are collection literals?

A collection literal is a syntactic expression that evaluates to an array, List , Map , or other aggregate type.

How do you use literals in Java?

Single quote: Java literal is specified to a char data type as a single character enclosed in a single quote. For example, char ch = 'a'; Char Literal: Java literal is specified as an integer literal representing the Unicode value of a char.

How do you declare a literal in Java?

// The hexa-decimal number should be prefix // with 0X or 0x. int x = 0X123Face; Binary literals: From 1.7 onward, we can specify literal value even in binary form also, allowed digits are 0 and 1. Literals value should be prefixed with 0b or 0B.

What is the use of literals?

Literals provide a means of expressing specific values in your program. For example, in the following statement, an integer variable named count is declared and assigned an integer value. The literal 0 represents, naturally enough, the value zero.


1 Answers

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) ); 
like image 168
Natix Avatar answered Nov 10 '22 02:11

Natix