ConcurrentSkipListSet first() method in Java


The ConcurrentSkipListSet class in Java is an implementation of the SortedSet interface that provides a concurrent, sorted set of elements. The first() method of ConcurrentSkipListSet returns the first (lowest) element currently in the set, or null if the set is empty.

Syntax:

public E first()

Example:

ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<>();
set.add(10);
set.add(20);
set.add(30);
System.out.println(set.first()); // Output: 10

If the set is empty, calling first() method will return null.

Example:

ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<>();
System.out.println(set.first()); // Output: null

Another way to get the first element of a ConcurrentSkipListSet is to use an iterator and call the next() method.

Example:

ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<>();
set.add(10);
set.add(20);
set.add(30);
Iterator<Integer> iterator = set.iterator();
if (iterator.hasNext()) {
    System.out.println(iterator.next()); // Output: 10
}


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.