RU | EN | DE

What are Collections?

Collections in Java are a framework (a set of classes and interfaces) that simplifies working with groups of objects: their storage, search, sorting, deletion, and so on. Instead of writing arrays and methods for adding/removing elements yourself, Java offers ready-made data structures. Collections reside in the java.util package and are unified in the Java Collections Framework (JCF).

Where are they used?

  • Data storage (e.g., a list of users or orders in an online store);
  • Search and filtering (e.g., all orders costing more than 100 €);
  • Sorting (by date, alphabet, etc.);
  • Working with unique data (e.g., a list of login names without duplicates);
  • Key-value mapping (application settings or a cache).

Why is it important to know?

  1. 90% of development tasks are related to data storage and processing.
  2. Collections save time—they are already optimized and tested.
  3. Many frameworks (Spring, Hibernate) use collections internally.

Main Collection Interfaces

Everything revolves around Collection and Map.

1) Collection Interface

Subdivided into:

  • List — ordered lists, allow duplicates.
    • Implementations: ArrayList, LinkedList, Vector, Stack.
  • Set — sets, unique elements.
    • Implementations: HashSet, LinkedHashSet, TreeSet.
  • Queue/Deque — queues (FIFO, LIFO).
    • Implementations: PriorityQueue, ArrayDeque.

2) Map Interface

Stores key-value pairs.

  • Implementations: HashMap, LinkedHashMap, TreeMap, Hashtable, ConcurrentHashMap.

Java Collections Framework Hierarchy

                Iterable
                   │
               Collection
      ┌────────────┼────────────────┐
      │            │                │
     List         Set          Queue/Deque
      │            │                │
  ┌───┴─────┐  ┌───┴─────────┐  ┌───┴─────────┐
  ArrayList     HashSet          PriorityQueue
  LinkedList    LinkedHashSet    ArrayDeque
  Vector        TreeSet
  Stack
 
    Map (Does not inherit from Collection)
     ┌─────────────┬─────────────────┐
  HashMap      LinkedHashMap       TreeMap
  Hashtable    ConcurrentHashMap

Differences in Collections

  • ArrayList — fast access by index, slow deletion in the middle.
  • LinkedList — slow access by index, fast addition/deletion.
  • HashSet — unique elements, order is not guaranteed.
  • LinkedHashSet — preserves insertion order.
  • TreeSet — stores elements in sorted order.
  • HashMap — key-value pairs, order is not guaranteed.
  • LinkedHashMap — preserves insertion order.
  • TreeMap — keys are automatically sorted.

Relationship with other concepts

  • Generics: Collections almost always use generics (e.g., List<String>).
  • Stream API: Collections are often converted into streams for convenient processing (list.stream().filter(...).map(...).collect(...)).
  • Multithreading: There are concurrent implementations (ConcurrentHashMap, CopyOnWriteArrayList).

Code Example

We will look at:

  • ListArrayList, LinkedList
  • SetHashSet, TreeSet
  • MapHashMap, TreeMap And understand their differences in practice.
import java.util.*;
public class CollectionsDemo {
  public static void main(String[] args) {
    // ====== LIST ======
     List<String> arrayList = new ArrayList<>();
     arrayList.add("Java");
     arrayList.add("Python");
     arrayList.add("C++");
     arrayList.add("Java"); // allows duplicates
 
     System.out.println("ArrayList: " + arrayList);
     List<String> linkedList = new LinkedList<>();
     linkedList.add("First");
     linkedList.add("Second");
     linkedList.add("Third");
 
     System.out.println("LinkedList: " + linkedList);
     // ====== SET ======
      Set<String> hashSet = new HashSet<>();
      hashSet.add("One");
      hashSet.add("Two");
      hashSet.add("Three");
      hashSet.add("Two"); // duplicate is ignored
 
      System.out.println("HashSet: " + hashSet);
      Set<String> treeSet = new TreeSet<>();
      treeSet.add("Banana");
      treeSet.add("Apple");
      treeSet.add("Orange");
 
      System.out.println("TreeSet (sorted): " + treeSet);
      // ====== MAP ======
      Map<Integer, String> hashMap = new HashMap<>();
      hashMap.put(1, "One");
      hashMap.put(2, "Two");
      hashMap.put(3, "Three");
      hashMap.put(2, "NewTwo"); // overwrites the value for key 2
 
      System.out.println("HashMap: " + hashMap);
      Map<Integer, String> treeMap = new TreeMap<>();
      treeMap.put(30, "Thirty");
      treeMap.put(10, "Ten");
      treeMap.put(20, "Twenty");
 
      System.out.println("TreeMap (sorted by key): " + treeMap);
  }
}
  • ArrayList — preserves order, allows duplicates. Output: [Java, Python, C++, Java].
  • LinkedList — also a list, but optimized for insertions/deletions.
  • HashSet — stores only unique elements, order is unpredictable.
  • TreeSet — unique + sorted.
  • HashMap — keys are unique, values can be overwritten.
  • TreeMap — keys are automatically sorted.

Common Mistakes

  1. Forgetting about generics:
List list = new ArrayList(); // raw type, bad

Better like this:

List<String> list = new ArrayList<>();
  1. Using the wrong collection:   - ArrayList instead of HashSet if you need unique values.   - LinkedList instead of ArrayList when there are many reads by index.
  2. Comparing using == instead of equals() for objects in collections.

Best Practices

  • Declare using the interface (List, Set, Map), not a specific class:
List<String> list = new ArrayList<>();
  • Choose a collection based on the task:   - fast access by index → ArrayList   - unique elements → HashSet   - sorting → TreeSet / TreeMap   - key-value → HashMap

Collections cheat sheet

List (ordered lists that allow duplicates)

ClassFeaturesWhen to Use
ArrayListFast index access O(1), slow insertion/deletion in the middleWhen there are many reads and few updates
LinkedListFast insertion/deletion O(1) at beginning/middle, slow index accessWhen frequent insertions/deletions needed
Vector / StackOld synchronized implementationsRarely used, prefer ArrayDeque instead

Set (sets, only unique elements)

ClassFeaturesWhen to Use
HashSetNo order, unique elements, fast lookup O(1)When only unique values are needed
LinkedHashSetMaintains insertion orderWhen unique values with order are needed
TreeSetAutomatically sortedWhen unique values with sorting are needed

Map (key–value)

ClassFeaturesWhen to Use
HashMapFast access O(1), order not guaranteedMost common option (cache, settings, etc.)
LinkedHashMapMaintains insertion orderWhen key order matters
TreeMapAutomatically sorted by keyWhen a sorted map is needed
ConcurrentHashMapThread-safe, non-blockingFor multithreaded environments

Queue / Deque (queues and stacks)

ClassFeaturesWhen to Use
ArrayDequeFaster than Stack and LinkedListFor stack (LIFO) or queue (FIFO)
PriorityQueueElements sorted by priorityFor priority-based queue

Tips

  • Declare using an interface:
List<String> list = new ArrayList<>();
  • For multithreading, use Concurrent versions (ConcurrentHashMap, CopyOnWriteArrayList).
  • For large datasets and filtering — it’s convenient to switch to the Stream API.