Collections in Java are built-in data structures that are used to store, manipulate, and process groups of objects. They provide a higher level of abstraction and offer a wide range of operations to perform on data, such as adding, removing, searching, sorting, and more. Java provides a comprehensive set of collection classes and interfaces that facilitate efficient and organized handling of data.
Here are some commonly used collection types in Java:
A List is an ordered collection that allows duplicate elements. It maintains the insertion order of elements.
List< Type > list = new ArrayList<>();
public class CollectionExamples { public static void main(String[] args) { // List Listnames = new ArrayList<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); System.out.println(names); // Output: [Alice, Bob, Charlie] } }
A Set is a collection that does not allow duplicate elements. It does not maintain any particular order of elements.
Setset = new HashSet<>();
public class CollectionExamples { public static void main(String[] args) { // Set Setnumbers = new HashSet<>(); numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(3); // Duplicate elements are ignored System.out.println(numbers); // Output: [1, 2, 3] } }
A Map is an object that maps keys to values. Each key in a Map must be unique, and it allows retrieval of values based on the keys.
Mapmap = new HashMap<>();
public class CollectionExamples { public static void main(String[] args) { // Map Mapages = new HashMap<>(); ages.put("Alice", 25); ages.put("Bob", 30); ages.put("Charlie", 35); System.out.println(ages.get("Bob")); // Output: 30 } }
A Queue is a collection that follows the First-In-First-Out (FIFO) principle. Elements are added at the end and removed from the beginning.
Queuequeue = new LinkedList<>();
public class CollectionExamples { public static void main(String[] args) { // Queue Queuetasks = new LinkedList<>(); tasks.add("Task 1"); tasks.add("Task 2"); tasks.add("Task 3"); System.out.println(tasks.poll()); // Output: Task 1 (removes and returns the head) } }
A Stack is a collection that follows the Last-In-First-Out (LIFO) principle. Elements are added and removed from the top.
Stackstack = new Stack<>();
Stack< String > books = new Stack<>(); books.push("Book 1"); books.push("Book 2"); books.push("Book 3"); System.out.println(books.pop()); // Output: Book 3 (removes and returns the top)
A Deque (Double Ended Queue) is a collection that allows insertion and removal of elements from both ends.
Dequedeque = new ArrayDeque<>();
public class CollectionExamples { public static void main(String[] args) { Dequedeque = new ArrayDeque<>(); deque.addFirst(1); deque.addLast(2); deque.addLast(3); System.out.println(deque.pollFirst()); // Output: 1 (removes and returns the first element) } }