JvJava
BeginnerLesson 6 of 16

Arrays, Lists, Maps & Sets – Java

The most important data structures of the Collections Framework.

An array has a fixed length and a fixed size. For flexible collections you use List, Set and Map from java.util.

import java.util.*;

int[] zahlen = {3, 1, 2};
Arrays.sort(zahlen);
System.out.println(Arrays.toString(zahlen));   // [1, 2, 3]
System.out.println(zahlen.length);             // 3

List<String> namen = new ArrayList<>();
namen.add("Ada");
namen.add("Linus");
namen.add(0, "Grace");
System.out.println(namen);                     // [Grace, Ada, Linus]
System.out.println(namen.get(1) + " " + namen.size());  // Ada 3
namen.remove("Ada");
System.out.println(namen.contains("Ada"));     // false

A Map assigns values to keys, a Set stores each value only once. List.of, Set.of and Map.of create immutable collections.

Map<String, Integer> alter = new HashMap<>();
alter.put("Ada", 36);
alter.put("Bob", 25);
alter.merge("Bob", 1, Integer::sum);           // Bob: 26
System.out.println(alter.get("Bob"));          // 26
System.out.println(alter.getOrDefault("Cy", -1)); // -1

Set<Integer> einzigartig = new TreeSet<>(List.of(3, 1, 2, 2, 3));
System.out.println(einzigartig);               // [1, 2, 3]

List<Integer> fest = List.of(1, 2, 3);         // immutable

Since Java 21, ordered collections have common methods for the beginning and the end (sequenced collections):

List<String> l = new ArrayList<>(List.of("a", "b", "c"));
System.out.println(l.getFirst() + " " + l.getLast());   // a c
System.out.println(l.reversed());                       // [c, b, a]
l.addFirst("z");
System.out.println(l);                                  // [z, a, b, c]
WarningList.of(...) is immutable: add throws an UnsupportedOperationException. A HashMap does not guarantee any order – use LinkedHashMap (insertion order) or TreeMap (sorted).
TipProgram against the interface: List<String> x = new ArrayList<>(); instead of ArrayList<String> x = .... That way you can swap the implementation later.