Skip to content
Java

Collection Operations

Common operations on List, Set, and Map.

By EZ4Code Team
collectionscollection

Code

import java.util.*;

// List
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
list.add("d");
list.remove(0);
String first = list.get(0);

// Set
Set<Integer> set = new HashSet<>(Set.of(1, 2, 3));
set.add(4);
set.contains(2);

// Map
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.getOrDefault("three", 0);

// Iterate
map.forEach((k, v) -> System.out.println(k + "=" + v));

// Immutable collection
List<String> immutable = List.of("x", "y", "z");
Map<String, Integer> immutableMap = Map.of("a", 1, "b", 2);

Explanation

The Java Collections Framework provides interfaces like List, Set, Map with multiple implementations.

More Java Snippets