🏷 Collections
10 patterns
Topic: Collections
All Java patterns related to Collections — java.evolved
Collections
Copying collections immutably
Old
List<String> copy =
Collections.unmodifiableList(
new ArrayList<>(original)
);
Modern
List<String> copy =
List.copyOf(original);
hover to see modern →
JDK 10+
learn more →
Collections
Immutable list creation
Old
List<String> list =
Collections.unmodifiableList(
new ArrayList<>(
Arrays.asList("a", "b", "c")
)
);
Modern
List<String> list =
List.of("a", "b", "c");
hover to see modern →
JDK 9+
learn more →
Collections
Immutable map creation
Old
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map = Collections.unmodifiableMap(map);
Modern
Map<String, Integer> map =
Map.of("a", 1, "b", 2, "c", 3);
hover to see modern →
JDK 9+
learn more →
Collections
Immutable set creation
Old
Set<String> set =
Collections.unmodifiableSet(
new HashSet<>(
Arrays.asList("a", "b", "c")
)
);
Modern
Set<String> set =
Set.of("a", "b", "c");
hover to see modern →
JDK 9+
learn more →
Collections
Map.entry() factory
Old
Map.Entry<String, Integer> e =
new AbstractMap.SimpleEntry<>(
"key", 42
);
Modern
var e = Map.entry("key", 42);
hover to see modern →
JDK 9+
learn more →
Collections
Reverse list iteration
Old
for (ListIterator<String> it =
list.listIterator(list.size());
it.hasPrevious(); ) {
String element = it.previous();
System.out.println(element);
}
Modern
for (String element : list.reversed()) {
IO.println(element);
}
hover to see modern →
JDK 21+
learn more →
Collections
Sequenced collections
Old
// Get last element
Object last = list.get(list.size() - 1);
// Get first
Object first = list.get(0);
// Reverse iteration: manual
Modern
var last = list.getLast();
var first = list.getFirst();
var reversed = list.reversed();
hover to see modern →
JDK 21+
learn more →
Collections
Typed stream toArray
Old
List<String> list = getNames();
List<String> filtered = new ArrayList<>();
for (String n : list) {
if (n.length() > 3) {
filtered.add(n);
}
}
String[] arr = filtered.toArray(new String[0]);
Modern
String[] arr = getNames().stream()
.filter(n -> n.length() > 3)
.toArray(String[]::new);
hover to see modern →
JDK 8+
learn more →
Collections
Unmodifiable collectors
Old
List<String> list = stream.collect(
Collectors.collectingAndThen(
Collectors.toList(),
Collections::unmodifiableList
)
);
Modern
List<String> list = stream.toList();
hover to see modern →
JDK 16+
learn more →
Streams
Stream.toList()
Old
List<String> result = stream
.filter(s -> s.length() > 3)
.collect(Collectors.toList());
Modern
List<String> result = stream
.filter(s -> s.length() > 3)
.toList();
hover to see modern →
JDK 16+
learn more →