In Java, collections are like containers that can hold multiple items. They help us store, organize, and manage groups of objects. Let's learn about some common types of collections: List, Set, and Map.
Collections are used to store and manage groups of objects. They provide various methods to add, remove, and access elements. Java provides a framework called the Collections Framework to work with collections easily.
A List is a collection that can hold a sequence of elements. You can access elements by their position (index) in the list. Lists can contain duplicate elements.
import java.util.ArrayList;
public class ListExample {
public static void main(String[] args) {
// Create an ArrayList to store names
ArrayList<String> names = new ArrayList<>();
// Add names to the list
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("Alice"); // Duplicate element
// Print the list
System.out.println("Names: " + names);
// Access an element by index
String name = names.get(1);
System.out.println("Name at index 1: " + name);
// Remove an element
names.remove(2);
System.out.println("Names after removing: " + names);
}
}
A Set is a collection that cannot contain duplicate elements. Sets are useful when you need to store unique items.
import java.util.HashSet;
public class SetExample {
public static void main(String[] args) {
// Create a HashSet to store unique numbers
HashSet<Integer> numbers = new HashSet<>();
// Add numbers to the set
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(20); // Duplicate element, will be ignored
// Print the set
System.out.println("Numbers: " + numbers);
}
}
A Map is a collection that stores key-value pairs. You can access values by their corresponding keys.
import java.util.HashMap;
public class MapExample {
public static void main(String[] args) {
// Create a HashMap to store names and ages
HashMap<String, Integer> people = new HashMap<>();
// Add entries to the map
people.put("Alice", 25);
people.put("Bob", 30);
people.put("Charlie", 20);
// Print the map
System.out.println("People: " + people);
// Access a value by key
int age = people.get("Bob");
System.out.println("Bob's age: " + age);
// Update a value
people.put("Alice", 26);
System.out.println("People after updating: " + people);
}
}
Collections are powerful tools in Java that help us work with groups of objects efficiently. By using the right type of collection, you can write more efficient and effective code.
<< Previous | Home | Next >>