Java Collections: List, Set, Map
In Java, the Collections framework provides a set of interfaces and classes to store and manipulate groups of objects. Common collection types include List, Set, and Map.
List Interface:
The List interface extends Collection and represents an ordered collection of elements that can contain duplicate values. Some common implementations are ArrayList and LinkedList.
// Example of using List
import java.util.List;
import java.util.ArrayList;
public class ListExample {
public static void main(String[] args) {
// Creating a List
List<String> fruits = new ArrayList<>();
// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Accessing elements
System.out.println("Fruits: " + fruits);
// Iterating through the list
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Set Interface:
The Set interface extends Collection and represents a collection of unique elements. Some common implementations are HashSet and TreeSet.
// Example of using Set
import java.util.Set;
import java.util.HashSet;
public class SetExample {
public static void main(String[] args) {
// Creating a Set
Set<String> colors = new HashSet<>();
// Adding elements
colors.add("Red");
colors.add("Green");
colors.add("Blue");
// Adding a duplicate element (ignored in a Set)
colors.add("Red");
// Accessing elements
System.out.println("Colors: " + colors);
// Iterating through the set
for (String color : colors) {
System.out.println(color);
}
}
}
Map Interface:
The Map interface represents a collection of key-value pairs. Some common implementations are HashMap and TreeMap.
// Example of using Map
import java.util.Map;
import java.util.HashMap;
public class MapExample {
public static void main(String[] args) {
// Creating a Map
Map<String, Integer> ages = new HashMap<>();
// Adding key-value pairs
ages.put("John", 25);
ages.put("Alice", 30);
ages.put("Bob", 28);
// Accessing values by key
System.out.println("Age of John: " + ages.get("John"));
// Iterating through the map
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue() + " years old");
}
}
}
Note:
The Collections framework in Java provides a powerful and flexible way to work with groups of objects. The List, Set, and Map interfaces, along with their various implementations, cater to different needs in terms of ordering, uniqueness, and key-value associations.