In this post, we will learn the differences between List and Set in Java with examples.

List: Represents an ordered collection (also known as a sequence) where elements can be accessed by their position in the list. Lists allow duplicate elements and maintain the order in which elements are inserted. Common implementations include ArrayList and LinkedList.

Set: Represents a collection that does not allow duplicate elements. Sets do not guarantee order by default, but certain implementations, like LinkedHashSet, maintain insertion order, while others, like TreeSet, maintain a sorted order. Sets are designed to prevent accidental or intentional duplicate entries.

Difference Between List and Set in Java

Criteria List Set
Ordering Ordered (based on insertion order or how it’s defined) Not necessarily ordered (though some implementations like LinkedHashSet maintain order)
Duplicates Allows duplicates Does not allow duplicates
Example Implementations ArrayList, LinkedList HashSet, LinkedHashSet, TreeSet
Null Elements Allows multiple null elements (based on implementation) Allows at most one null element (based on implementation)
Method to add elements add(index, element) add(element)
Interfaces it extends extends Collection interface extends Collection interface

Example

This demonstration provides a basic understanding of the primary differences between List and Set in Java. Note that there are other implementations of List and Set that might offer additional features or performance characteristics, but the key differences demonstrated remain the same across implementations.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ListVsSetDemo {

    public static void main(String[] args) {

        // Create a List and add some elements
        List<String> sampleList = new ArrayList<>();
        sampleList.add("apple");
        sampleList.add("banana");
        sampleList.add("apple");
        sampleList.add("orange");

        System.out.println("List:");
        sampleList.forEach(System.out::println);

        // Create a Set and add some elements
        Set<String> sampleSet = new HashSet<>();
        sampleSet.add("apple");
        sampleSet.add("banana");
        sampleSet.add("apple");
        sampleSet.add("orange");

        System.out.println("\nSet:");
        sampleSet.forEach(System.out::println);
    }
}

Output:

List:
apple
banana
apple
orange

Set:
apple
banana
orange

Explanation:

1. List: A List is an ordered collection that can contain duplicate elements. It maintains the order of insertion.

2. Set: A Set is an unordered collection that cannot contain duplicate elements. It ensures that there are no duplicates.

3. In the given example, the sampleList (which is an ArrayList) allows the duplicate entry of "apple".

4. The sampleSet (which is a HashSet) does not allow the duplicate entry of "apple", and hence, only one occurrence of "apple" is stored and displayed.