Collection
In Java, the term "Collections" refers to data structures that store and manipulate groups of objects. The Java Collections Framework provides several interfaces and classes for implementing and organizing collections. Here are the main types of collections in Java along with examples:
1. List Interface:
Description: Lists are ordered collections that allow duplicate elements.
Example Code:
import java.util.List;
import java.util.ArrayList;
public class ListExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
// Adding elements to the list
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Accessing elements by index
System.out.println("First name: " + names.get(0));
// Iterating through the list
System.out.println("Names:");
for (String name : names) {
System.out.println(name);
}
}
}2. Set Interface:
Description: Sets are unordered collections that do not allow duplicate elements.
Example Code:
3. Map Interface:
Description: Maps store key-value pairs, where each key is associated with exactly one value.
Example Code:
4. Queue Interface:
Description: Queues represent a collection used to hold multiple elements before processing.
Example Code:
5. Stack Class:
Description: A stack is a collection that uses the Last-In-First-Out (LIFO) order.
Example Code:
These examples showcase various types of collections in Java along with their basic operations. The Java Collections Framework provides a rich set of interfaces and classes that can be utilized to solve a wide range of programming problems involving collections of data.
Last updated