List vs Set vs Map in Java

Advertisement

Quick Answer

  • List — an ordered collection that allows duplicates, accessed by index. "Many values."
  • Set — a collection of unique values; duplicates are ignored. "Unique values."
  • Map — key–value pairs with unique keys, accessed by key. "Look it up by name."

List and Set extend the Collection interface; Map is a separate interface — it isn't a Collection, because it stores pairs rather than single elements.

Comparison at a Glance

Aspect List Set Map
Stores Values Unique values Key → value pairs
Duplicates Allowed Not allowed Keys unique; values can repeat
Order Insertion order, index-based Depends on implementation Depends on implementation
Access get(index) Iterate or contains() get(key)
Nulls Allowed HashSet: one null; TreeSet: none HashMap: one null key; TreeMap: no null key
Main implementations ArrayList, LinkedList HashSet, LinkedHashSet, TreeSet HashMap, LinkedHashMap, TreeMap
In Selenium frameworks Web elements, test rows Window handles, unique values Test data, configuration

List — Ordered, Duplicates Allowed

List<String> browsers = new ArrayList<>(
        List.of("chrome", "firefox", "chrome")
);

System.out.println(
        browsers +
        " size=" + browsers.size() +
        " first=" + browsers.get(0)
);

// [chrome, firefox, chrome] size=3 first=chrome
  • ArrayList — fast access by index; the default choice.
  • LinkedList — cheaper insertions and removals at the ends; slower random access.

In Selenium: driver.findElements() returns a List<WebElement> because a page can have several matching elements, in document order:

List<WebElement> rows =
        driver.findElements(
                By.cssSelector("table#orders tbody tr")
        );

Assert.assertEquals(rows.size(), 5);

Set — Unique Values Only

Set<String> unique = new LinkedHashSet<>(browsers);

System.out.println(
        unique + " add chrome again? " + unique.add("chrome")
);

// [chrome, firefox] add chrome again? false

Set<String> sorted =
        new TreeSet<>(List.of("qa", "dev", "prod"));

System.out.println(sorted);

// [dev, prod, qa]
Implementation Order Typical use
HashSet No guaranteed order Fast uniqueness checks
LinkedHashSet Insertion order Removing duplicates while keeping order
TreeSet Sorted Unique values in sorted order

In Selenium: driver.getWindowHandles() returns a Set<String> because every window handle is unique:

String parent = driver.getWindowHandle();

for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(parent)) {
        driver.switchTo().window(handle);
    }
}

add() returning false for a duplicate is also handy for checks like "are all product names on this page unique?"

Map — Key–Value Pairs

Map<String, String> config = new LinkedHashMap<>();

config.put("browser", "chrome");
config.put("env", "qa");

String old = config.put("browser", "firefox");
// Same key → value replaced

System.out.println(
        config +
        " replaced=" + old +
        " missing=" + config.getOrDefault("timeout", "10")
);

// {browser=firefox, env=qa} replaced=chrome missing=10

for (Map.Entry<String, String> e : config.entrySet()) {
    System.out.println(e.getKey() + "=" + e.getValue());
}
Implementation Order Typical use
HashMap No guaranteed order General-purpose lookups — the default
LinkedHashMap Insertion order Config and test data where order matters in output
TreeMap Sorted by key Sorted reports, frequency counts in key order

A classic interview program — character frequency — is a Map job:

Map<Character, Integer> freq = new TreeMap<>();

for (char c : "banana".toCharArray()) {
    freq.merge(c, 1, Integer::sum);
}

System.out.println(freq);

// {a=3, b=1, n=2}

The Data-Driven Pattern: List<Map<String, String>>

Each Map is one test record (field → value) and the List holds all the records — a structure you'll see in almost every data-driven framework, whether the data comes from Excel, JSON or a database:

List<Map<String, String>> testData = List.of(
        Map.of(
                "username", "asha",
                "password", "Secret@1"
        ),
        Map.of(
                "username", "ravi",
                "password", "Secret@2"
        )
);

for (Map<String, String> row : testData) {
    loginPage.login(
            row.get("username"),
            row.get("password")
    );
}

More: Data-Driven Testing.

Nulls and Performance

  • Nulls: HashSet allows one null and HashMap allows one null key; TreeSet and TreeMap throw NullPointerException for null, because they must compare elements to sort them (verified in the demo).
  • Performance: HashSet and HashMap give roughly constant-time add, remove and lookup; the Tree versions are logarithmic (they keep things sorted); ArrayList.get(index) is constant-time, but ArrayList.contains() scans the whole list.
  • Rule of thumb: if you often ask "is this value in the collection?", use a Set, not a List.

Step through these examples line by line in the Java Code Visualizer to see how each collection changes.

Which Collection Should You Use?

You need… Use
Ordered values, duplicates OK, access by position ArrayList
Unique values, fast "contains" checks HashSet
Unique values in insertion order LinkedHashSet
Unique values, sorted TreeSet
Look up a value by a key HashMap
Key–value pairs in insertion order LinkedHashMap
Key–value pairs sorted by key TreeMap
Many records with many fields List<Map<String, String>>

From Real Projects

Java has been the language of every automation framework I've worked with — Selenium, TestNG, POM classes and Apache POI for Excel data. Interviews for automation roles regularly include basic programs like this one, often followed by a question on OOP concepts. Practice writing it by hand and explaining how you'd test it. On Canolog, the many forms and screens across sales, inventory, finance and service are where keeping page details in POM classes and reusable steps in a business library paid off. If you need duplicates removed, reach for a Set; if you need lookup by key, a Map.

📚 Official documentation: Oracle Java Tutorials: Collections · dev.java: Learn Java (Oracle)

Frequently Asked Questions

What is the difference between List, Set and Map?

A List keeps order and allows duplicates; a Set stores only unique values; a Map stores key–value pairs with unique keys.

Is Map part of the Collection interface?

No. List and Set extend Collection; Map is a separate interface in the Collections Framework because it stores pairs.

Why does Selenium return a Set for window handles?

Window handles are always unique, so a Set is the natural type — getWindowHandles() returns Set<String>.

Why does findElements() return a List?

A page can contain several matching elements, in a meaningful order, so a List is used — and it's empty (not an exception) when nothing matches.

What is the difference between HashSet and HashMap?

A HashSet stores unique values; a HashMap stores key–value pairs with unique keys. Internally, HashSet is backed by a HashMap.

HashMap vs LinkedHashMap vs TreeMap?

HashMap has no guaranteed order; LinkedHashMap keeps insertion order; TreeMap keeps keys sorted.

What is List<Map<String, String>> used for?

Data-driven testing: each Map is one test record and the List holds all the records.