CODE STRUCTURE

Java collections

The Java Collections Framework is a set of interfaces, classes and common methods for storing, finding, grouping and managing multiple objects.

What are collections for?

An array's size is fixed at creation. A collection can grow or shrink while the program runs and provides methods for adding, removing, searching and traversing elements.

Comparing an array and a collection
PropertyThe arrayCollection
SizeSet at creationUsually can change
ElementsCan also store primitive typesStores objects; uses wrapper classes for primitives
OperationsBasic operations use manual code or ArraysProvides methods such as add(), remove(), contains()

For example, List<Integer> stores Integer objects. Java can automatically convert int to Integer; this is called autoboxing.

Interfaces and their implementing classes

An interface specifies which operations a collection must support. A concrete class decides how to implement them.

Main Collections Framework interfaces
InterfaceCommon classesPurpose
ListArrayList, LinkedListPreserves order, allows duplicates and supports index-based access.
SetHashSet, LinkedHashSet, TreeSetStores only unique elements.
Queue / DequeArrayDeque, LinkedListManages elements in processing order or allows operations at both ends.
MapHashMap, LinkedHashMap, TreeMapStores key-value pairs; each key is unique.
Map does not extend the Collection interface.

Map belongs to the Collections Framework but forms a separate hierarchy of key-value pairs. List, Set and Queue belong to the Collection hierarchy.

List: an ordered list

import java.util.ArrayList;
import java.util.List;

List<String> pirkiniai = new ArrayList<>();
pirkiniai.add("duona");
pirkiniai.add("pienas");
pirkiniai.add("duona");

System.out.println(pirkiniai);
System.out.println(pirkiniai.get(1));
Console output

[duona, pienas, duona]
pienas

  1. The variable's type is the interface List<String>, while the object is created using ArrayList.
  2. <String> specifies that the list can store only strings.
  3. List allows two identical duona values.
  4. get(1) retrieves the second element because indices start at zero.

Set: unique values

import java.util.HashSet;
import java.util.Set;

Set<String> miestai = new HashSet<>();
miestai.add("Vilnius");
miestai.add("Kaunas");
miestai.add("Vilnius");

System.out.println(miestai.size());
System.out.println(miestai.contains("Kaunas"));
Console output

2
true

Vilnius is added twice, but Set does not duplicate it. HashSet does not guarantee element output order, so the example checks the size and whether a particular city is present.

Map: keys and values

import java.util.HashMap;
import java.util.Map;

Map<String, Integer> pazymiai = new HashMap<>();
pazymiai.put("Ieva", 9);
pazymiai.put("Mantas", 8);
pazymiai.put("Ieva", 10);

System.out.println(pazymiai.get("Ieva"));
System.out.println(pazymiai.size());
Console output

10
2

  1. Map<String, Integer> uses a name as the key and a grade as the value.
  2. put("Ieva", 9) stores the first grade.
  3. Assigning the same key a later value of 10replaces the previous value.
  4. Two unique keys remain in the map.

Traversing a collection

List<String> vardai = List.of("Rūta", "Jonas", "Aistė");

for (String vardas : vardai) {
    System.out.println(vardas);
}
Console output

Rūta
Jonas
Aistė

for-each loop takes each collection element in turn. More complex cases can use an Iterator, forEach() or the Stream API.

How do you choose a collection?

  • Choose Listwhen order or indices matter, or duplicates are allowed.
  • Choose Setwhen every value must be unique.
  • Choose Mapwhen a value must be found by a unique key.
  • Choose Queuewhen elements must be processed in a defined order.

To begin with, these are usually enough: ArrayList, HashSet, HashMap and ArrayDeque.

Common methods

What collection methods do
The methodPurpose
add()Adds an element to a Collection.
remove()Removes an element.
contains()Checks whether the collection contains an element.
size()Returns the element count.
isEmpty()Checks whether the collection is empty.
clear()Removes all elements.
put() / get()Stores or retrieves a Map value by its key.