Course – LS – All

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

>> CHECK OUT THE COURSE

1. Overview

A Set is a collection of items with no duplicates. Java provides a Set interface and several implementations of that interface for us to use. This tutorial will look at how to get the first item from a Set. A Java Set is unordered by definition, however, there are implementations that do maintain order, such as LinkedHashSet, which we’ll focus on here.

2. Using Iterator

We can retrieve the first element in a Set using an Iterator. The Set interface allows us to get an Iterator for all implementations using the iterator() method. We can then call next() on the Iterator to get the first item:

@Test
void givenASet_whenUsingIterator_thenRetrieveAnItem() {
    Set<Integer> set = new LinkedHashSet<>(Arrays.asList(1, 2, 3, 4, 5));
    Iterator iterator = set.iterator();
    if (iterator.hasNext()) {
        int retrieved = (int) iterator.next();
        assertEquals(retrieved, 1);
    }
}

We’ve instantiated a LinkedHashSet here filled with five Integers. Our assert at the end shows we’ve successfully retrieved the first element from the Set.

If our Set is empty, or there are no more elements in our Iterator, next() will throw NoSuchElementException. We have protected against that here by using Iterators hasNext() method before trying to fetch the next item. If our use case is simply to get the first and only the first item, we could have checked the Set wasn’t empty before using the Iterator instead.

3. Using Streams

The second option to get the first item out of a Set is using Streams. We can convert the Set into a Stream using the stream() method. Following that, we can use the Streams findFirst() method, which will return an Optional. Finally, we call get() on the Optional to retrieve our item:

@Test
void givenASet_whenUsingStreams_thenRetrieveAnItem() {
    Set<Integer> set = new LinkedHashSet<>(Arrays.asList(1, 2, 3, 4, 5));
    Optional<Integer> optional = set.stream().findFirst();
    if (optional.isPresent()) {
        int retrieved = optional.get();
        assertEquals(retrieved, 1);
    }
}

This code carries the same risk as we saw in the previous section, where if there are no items in the Set, we’ll get NoSuchElementException when calling get() on the Optional. To protect against this, we’ve used ifPresent() on the Optional before attempting to retrieve the value.

Using Streams like this opens up a lot more options for post-processing of the items retrieved from the Set. For example, we could have immediately chained ifPresent() onto findFirst() and passed in a Consumer to do something with the item. We could also have used Streams sorted() method to redefine the order and, therefore, what the first item will be.

4. Conclusion

In this article, we’ve seen two ways of getting the first item from a Set, specifically the LinkedHashSet implementation as it’s ordered. Using an Iterator provides a simple way to retrieve the first item, and we could loop over all the items if needed. Using Streams provides the same functionality but opens up a lot more options for actually doing things with the retrieved item straight away and allows us to control the order in which we look at the items.

As always, the full code for the examples is available over on GitHub.

Course – LS – All

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

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.