File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
spring-core/src/main/java/org/springframework/util Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -355,6 +355,45 @@ public static <T> T lastElement(@Nullable List<T> list) {
355
355
return list .get (list .size () - 1 );
356
356
}
357
357
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
+
358
397
/**
359
398
* Marshal the elements from the given enumeration into an array of the given type.
360
399
* Enumeration elements must be assignable to the type of the given array. The array
You can’t perform that action at this time.
0 commit comments