From d503bc2804b7bdbb9e9c46081a7fa454ac81c8d7 Mon Sep 17 00:00:00 2001 From: Vitalii Rastvorov Date: Wed, 4 Dec 2019 18:18:46 +0200 Subject: [PATCH] Add firstElement to CollectionUtils --- .../springframework/util/CollectionUtils.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/spring-core/src/main/java/org/springframework/util/CollectionUtils.java b/spring-core/src/main/java/org/springframework/util/CollectionUtils.java index 79798b9f5448..79f5185796e1 100644 --- a/spring-core/src/main/java/org/springframework/util/CollectionUtils.java +++ b/spring-core/src/main/java/org/springframework/util/CollectionUtils.java @@ -355,6 +355,45 @@ public static T lastElement(@Nullable List 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 firstElement(@Nullable Set set) { + if (isEmpty(set)) { + return null; + } + if (set instanceof SortedSet) { + return ((SortedSet) set).first(); + } + + Iterator 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 firstElement(@Nullable List 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