Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Java collections

Java collections: The Java Collections Framework separates Collection, List, Set, Queue, and Map interfaces from implementations, with equality, ordering, and mutability contracts determined by the type.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

collections

The Java Collections Framework separates Collection, List, Set, Queue, and Map interfaces from implementations, with equality, ordering, and mutability contracts determined by the type.

Choose ArrayList for indexed access, HashSet or HashMap for lookup by a stable hash, and a concurrent collection for cross-thread sharing.

Mutating key fields used by equals or hashCode breaks lookup; a fail-fast iterator detects modification only on a best-effort basis and provides no synchronization.

List.of rejects null and is unmodifiable, Arrays.asList is a fixed-size array-backed view, and Collections.unmodifiableList still reflects changes to its backing list.

The three lines [b, a, b], [b, a], and {b=2, a=1} demonstrate List duplicates, LinkedHashSet uniqueness and order, and LinkedHashMap counting respectively.

Examples

import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        List<String> items = List.of("b", "a", "b");
        Set<String> unique = new LinkedHashSet<>(items);
        Map<String, Integer> counts = new LinkedHashMap<>();
        items.forEach(item -> counts.merge(item, 1, Integer::sum));

        System.out.println(items);
        System.out.println(unique);
        System.out.println(counts);
    }
}

Result

[b, a, b]
[b, a]
{b=2, a=1}

The three lines [b, a, b], [b, a], and {b=2, a=1} demonstrate List duplicates, LinkedHashSet uniqueness and order, and LinkedHashMap counting respectively.

Sources