Skip to content

Commit

Permalink
Add firstElement to CollectionUtils
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaliirastvorov authored and jhoeller committed Dec 5, 2019
1 parent 14ce84c commit d503bc2
Showing 1 changed file with 39 additions and 0 deletions.
Expand Up @@ -355,6 +355,45 @@ public static <T> T lastElement(@Nullable List<T> list) {
return list.get(list.size() - 1);
}

/**
* Retrieve the first element of the given Set, using {@link SortedSet#first()}
* or otherwise using the iterator.
* @param set the Set to check (may be {@code null} or empty)
* @return the first element, or {@code null} if none
* @see SortedSet
* @see LinkedHashMap#keySet()
* @see java.util.LinkedHashSet
*/
@Nullable
public static <T> T firstElement(@Nullable Set<T> set) {
if (isEmpty(set)) {
return null;
}
if (set instanceof SortedSet) {
return ((SortedSet<T>) set).first();
}

Iterator<T> it = set.iterator();
T first = null;
if (it.hasNext()) {
first = it.next();
}
return first;
}

/**
* Retrieve the first element of the given List, accessing the zero index.
* @param list the List to check (may be {@code null} or empty)
* @return the first element, or {@code null} if none
*/
@Nullable
public static <T> T firstElement(@Nullable List<T> list) {
if (isEmpty(list)) {
return null;
}
return list.get(0);
}

/**
* Marshal the elements from the given enumeration into an array of the given type.
* Enumeration elements must be assignable to the type of the given array. The array
Expand Down

1 comment on commit d503bc2

@sbrannen
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See #24135

Please sign in to comment.