Introduction and Examples of List, Set, and Map Interfaces in Java

8/16/2025

#Introduction Examples of List, Set, and Map Interfaces in Java

Go Back

Introduction and Examples of List, Set, and Map Interfaces in Java

The Java Collections Framework provides powerful interfaces to store and manipulate groups of objects. Among them, List, Set, and Map are the most widely used. Each interface has its own purpose, strengths, and implementations.


#Introduction  Examples of List, Set, and Map Interfaces in Java

1. List Interface

  • Definition: A List is an ordered collection that allows duplicate elements.

  • Common Implementations: ArrayList, LinkedList, Vector

  • Use Case: Useful when you want to maintain insertion order and allow duplicates.

Example:

import java.util.*;

public class ListExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Apple"); // Duplicate allowed
        System.out.println(fruits); // [Apple, Banana, Apple]
    }
}

2. Set Interface

  • Definition: A Set is a collection that does not allow duplicate elements.

  • Common Implementations: HashSet, LinkedHashSet, TreeSet

  • Use Case: Useful when you want unique elements without duplicates.

Example:

import java.util.*;

public class SetExample {
    public static void main(String[] args) {
        Set<Integer> numbers = new HashSet<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(10); // Duplicate ignored
        System.out.println(numbers); // [20, 10]
    }
}

3. Map Interface

  • Definition: A Map is a collection of key-value pairs. Each key is unique, but values can be duplicated.

  • Common Implementations: HashMap, LinkedHashMap, TreeMap

  • Use Case: Useful when you need to store data in key-value format, like a dictionary.

Example:

import java.util.*;

public class MapExample {
    public static void main(String[] args) {
        Map<Integer, String> students = new HashMap<>();
        students.put(1, "John");
        students.put(2, "Alice");
        students.put(3, "Bob");
        System.out.println(students); // {1=John, 2=Alice, 3=Bob}
    }
}

Key Differences Between List, Set, and Map

FeatureListSetMap
OrderMaintains insertion orderNo guaranteed order (depends on implementation)Key-value pairs (keys unique)
DuplicatesAllowedNot allowedKeys not allowed, values allowed
Access MethodBy indexBy elementBy key

Best Practices

  • Use List when you need duplicates or ordered data.

  • Use Set for uniqueness.

  • Use Map for key-value lookups.

  • Choose the right implementation (ArrayList, HashSet, HashMap) based on performance requirements.


Final Thoughts

The List, Set, and Map interfaces are at the heart of the Java Collections Framework. Mastering these will make you more effective at writing scalable, efficient, and clean Java code.

Table of content