Course – LS – All

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we'll discuss the differences between Set and List in Java with the help of a simple example.

2. Conceptual Difference

Both List and Set are members of Java Collections. However, there are a few important differences:

  • A List can contain duplicates, but a Set can't
  • A List will preserve the order of insertion, but a Set may or may not
  • Since insertion order may not be maintained in a Set, it doesn't allow index-based access as in the List

Please note that there are a few implementations of the Set interface which maintain order, for example, LinkedHashSet.

3. Code Example

3.1. Allowing Duplicates

Adding a duplicate item is allowed for a List. However, it isn't for a Set:

@Test
public void givenList_whenDuplicates_thenAllowed(){
    List<Integer> integerList = new ArrayList<>();
    integerList.add(2);
    integerList.add(3);
    integerList.add(4);
    integerList.add(4);
    assertEquals(integerList.size(), 4);
}
@Test
public void givenSet_whenDuplicates_thenNotAllowed(){
    Set<Integer> integerSet = new HashSet<>();
    integerSet.add(2);
    integerSet.add(3);
    integerSet.add(4);
    integerSet.add(4);
    assertEquals(integerSet.size(), 3);
}

3.2. Maintaining Insertion Order

A Set maintains order depending on the implementation. For example, a HashSet is not guaranteed to preserve order, but a LinkedHashSet is. Let's see an example of ordering with LinkedHashSet:

@Test
public void givenSet_whenOrdering_thenMayBeAllowed(){
    Set<Integer> set1 = new LinkedHashSet<>();
    set1.add(2);
    set1.add(3);
    set1.add(4);
    Set<Integer> set2 = new LinkedHashSet<>();
    set2.add(2);
    set2.add(3);
    set2.add(4);
    Assert.assertArrayEquals(set1.toArray(), set2.toArray());
}

Since a Set is not guaranteed to maintain order, it can't be indexed.

4. Conclusion

In this tutorial, we saw the difference between a List and a Set in Java.

The source code is available over on GitHub.

Course – LS – All

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!