w1coding.comAll tutorials

Java Collections

Java lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Control
  5. Loops
  6. Arrays
  7. Methods
  8. OOP
  9. Contractors
  10. Inheritance
  11. Polymorphism
  12. Abtract
  13. Interfaces
  14. Constructors
  15. Static
  16. Exception
  17. Collections
  18. Lambda
  19. Streams
  20. Strings
  21. Date
  22. Interface
  23. Inheritance
  24. Polymorphism
  25. Exception
  26. File

Java Collections Framework

The Java Collections Framework provides a set of interfaces and classes for working with groups of objects. It includes lists, sets, and maps, which are commonly used to store and manipulate data.

List Interface

import java.util.ArrayList;
import java.util.List;

public class CollectionsExample {
    public static void main(String[] args) {
        List names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        System.out.println("Names List: " + names);
    }
}
    

The List interface is used to store ordered collections. The ArrayList class is one of the implementations of the List interface, which allows dynamic resizing.

Set Interface

import java.util.HashSet;
import java.util.Set;

public class CollectionsExample {
    public static void main(String[] args) {
        Set uniqueNames = new HashSet<>();
        uniqueNames.add("Alice");
        uniqueNames.add("Bob");
        uniqueNames.add("Alice");  // Duplicate value

        System.out.println("Unique Names Set: " + uniqueNames);
    }
}
    

The Set interface is used to store unique elements. The HashSet class is one of the implementations, and it automatically removes duplicates from the collection.

Map Interface

import java.util.HashMap;
import java.util.Map;

public class CollectionsExample {
    public static void main(String[] args) {
        Map phoneBook = new HashMap<>();
        phoneBook.put("Alice", 12345);
        phoneBook.put("Bob", 67890);

        System.out.println("Phone Book: " + phoneBook);
    }
}
    

The Map interface stores key-value pairs. In this example, a HashMap is used to associate names with phone numbers.