Java: Data structures – code examples
Working with lists
Use case: Manage collections of values: add, sort, filter.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> zahlen = new ArrayList<>(List.of(5, 3, 8, 1));
zahlen.add(10);
Collections.sort(zahlen);
System.out.println(zahlen);
System.out.println(zahlen.stream().filter(z -> z > 3).map(z -> z * 2).toList());
System.out.println(zahlen.size() + " " + Collections.max(zahlen));
}
}List.of is immutable, so we copy into an ArrayList. The stream filters and transforms like a list comprehension. Output: [1, 3, 5, 8, 10], [10, 16, 20], 5 10.
Map (dictionary)
Use case: Store mappings, e.g. configurations or counters per key.
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Object> person = new LinkedHashMap<>();
person.put("name", "Ada");
person.put("alter", 36);
person.put("stadt", "London");
for (var e : person.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
System.out.println(person.getOrDefault("email", "no email"));
}
}LinkedHashMap keeps the insertion order. getOrDefault returns a fallback value instead of null if the key is missing.
Sorting with Comparator
Data structures#sort#comparator#record
Use case: Order records by several fields, e.g. users by age, then name.
import java.util.*;
public class Main {
record Nutzer(String name, int alter) {}
public static void main(String[] args) {
var liste = new ArrayList<>(List.of(
new Nutzer("Ada", 36), new Nutzer("Bob", 25), new Nutzer("Cy", 36)));
liste.sort(Comparator.comparingInt(Nutzer::alter).reversed()
.thenComparing(Nutzer::name));
System.out.println(liste.stream().map(Nutzer::name).toList());
}
}comparingInt sorts by age, reversed reverses the order, thenComparing decides on a tie. Output: [Ada, Cy, Bob].