Diamond operator
Diamond operator now works with anonymous classes too.
Code Comparison
✕ Java 7/8
Map<String, List<String>> map =
new HashMap<String, List<String>>();
// anonymous class: no diamond
Predicate<String> p =
new Predicate<String>() {
public boolean test(String s) {..}
};
✓ Java 9+
Map<String, List<String>> map =
new HashMap<>();
// Java 9: diamond with anonymous classes
Predicate<String> p =
new Predicate<>() {
public boolean test(String s) {..}
};
Why the modern way wins
Consistent rules
Diamond works everywhere — constructors and anonymous classes alike.
Less redundancy
Type arguments are stated once on the left, never repeated.
DRY principle
The compiler already knows the type — why write it twice?
Old Approach
Repeat Type Args
Modern Approach
Diamond <>
Since JDK
9
Difficulty
beginner
JDK Support
Diamond operator
Available
Diamond with anonymous classes since JDK 9 (Sept 2017).
How it works
Java 7 introduced <> but it didn't work with anonymous inner classes. Java 9 fixed this, so you never need to repeat type arguments on the right-hand side.