Skip to content

Commit d503bc2

Browse files
vitaliirastvorovjhoeller
authored andcommitted
Add firstElement to CollectionUtils
1 parent 14ce84c commit d503bc2

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

spring-core/src/main/java/org/springframework/util/CollectionUtils.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,45 @@ public static <T> T lastElement(@Nullable List<T> list) {
355355
return list.get(list.size() - 1);
356356
}
357357

358+
/**
359+
* Retrieve the first element of the given Set, using {@link SortedSet#first()}
360+
* or otherwise using the iterator.
361+
* @param set the Set to check (may be {@code null} or empty)
362+
* @return the first element, or {@code null} if none
363+
* @see SortedSet
364+
* @see LinkedHashMap#keySet()
365+
* @see java.util.LinkedHashSet
366+
*/
367+
@Nullable
368+
public static <T> T firstElement(@Nullable Set<T> set) {
369+
if (isEmpty(set)) {
370+
return null;
371+
}
372+
if (set instanceof SortedSet) {
373+
return ((SortedSet<T>) set).first();
374+
}
375+
376+
Iterator<T> it = set.iterator();
377+
T first = null;
378+
if (it.hasNext()) {
379+
first = it.next();
380+
}
381+
return first;
382+
}
383+
384+
/**
385+
* Retrieve the first element of the given List, accessing the zero index.
386+
* @param list the List to check (may be {@code null} or empty)
387+
* @return the first element, or {@code null} if none
388+
*/
389+
@Nullable
390+
public static <T> T firstElement(@Nullable List<T> list) {
391+
if (isEmpty(list)) {
392+
return null;
393+
}
394+
return list.get(0);
395+
}
396+
358397
/**
359398
* Marshal the elements from the given enumeration into an array of the given type.
360399
* Enumeration elements must be assignable to the type of the given array. The array

0 commit comments

Comments
 (0)