java8 and further
Set<String> set = new TreeSet<>();
set.add("2");
set.add("1");
set.add("3");
String first = set.stream().findFirst().get();
This will help you retrieve the first element of the list or set.
Given that the set or list is not empty (get()
on empty optional will throw java.util.NoSuchElementException
)
orElse()
can be used as: (this is just a work around - not recommended)
String first = set.stream().findFirst().orElse("");
set.removeIf(String::isEmpty);
Below is the appropriate approach :
Optional<String> firstString = set.stream().findFirst();
if(firstString.isPresent()){
String first = firstString.get();
}
Similarly first element of the list can be retrieved.
Hope this helps.