File tree 2 files changed +60
-0
lines changed
main/java/com/jnape/palatable/lambda/functions/builtin/fn1
test/java/com/jnape/palatable/lambda/functions/builtin/fn1
2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .jnape .palatable .lambda .functions .builtin .fn1 ;
2
+
3
+ import com .jnape .palatable .lambda .functions .Fn1 ;
4
+
5
+ import java .util .Optional ;
6
+
7
+ /**
8
+ * Retrieve the last element of an <code>Iterable</code>, wrapped in an <code>Optional</code>. If the
9
+ * <code>Iterable</code> is empty, the result is <code>Optional.empty()</code>.
10
+ *
11
+ * @param <A> the Iterable element type
12
+ */
13
+ public final class Last <A > implements Fn1 <Iterable <A >, Optional <A >> {
14
+
15
+ private static final Last INSTANCE = new Last ();
16
+
17
+ private Last () {
18
+ }
19
+
20
+ @ Override
21
+ public Optional <A > apply (Iterable <A > as ) {
22
+ A last = null ;
23
+ for (A a : as ) {
24
+ last = a ;
25
+ }
26
+ return Optional .ofNullable (last );
27
+ }
28
+
29
+ @ SuppressWarnings ("unchecked" )
30
+ public static <A > Last <A > last () {
31
+ return (Last <A >) INSTANCE ;
32
+ }
33
+
34
+ public static <A > Optional <A > last (Iterable <A > as ) {
35
+ return Last .<A >last ().apply (as );
36
+ }
37
+ }
Original file line number Diff line number Diff line change
1
+ package com .jnape .palatable .lambda .functions .builtin .fn1 ;
2
+
3
+ import org .junit .Test ;
4
+
5
+ import java .util .Optional ;
6
+
7
+ import static com .jnape .palatable .lambda .functions .builtin .fn1 .Last .last ;
8
+ import static java .util .Arrays .asList ;
9
+ import static java .util .Collections .emptyList ;
10
+ import static org .junit .Assert .assertEquals ;
11
+
12
+ public class LastTest {
13
+
14
+ @ Test
15
+ public void presentForNonEmptyIterable () {
16
+ assertEquals (Optional .of (3 ), last (asList (1 , 2 , 3 )));
17
+ }
18
+
19
+ @ Test
20
+ public void emptyForEmpyIterables () {
21
+ assertEquals (Optional .empty (), last (emptyList ()));
22
+ }
23
+ }
You can’t perform that action at this time.
0 commit comments