Java 101Diamond Operator in Java

time to read 1 min | 63 words

Since Java 7 it’s not necessary to declare the type parameter twice while instantiating objects like Maps, Sets and Lists.

Consider the following code:

Map<String, List<String>> phoneBook = new HashMap<String, List<String>>();

The type parameter for HashMap in the right hand side of the expression seems redundant. This can be shortened using an empty “Diamond Operator” to give:

Map<String, List<String>> phoneBook = new HashMap<>();