File tree Expand file tree Collapse file tree
main/java/com/jnape/palatable/lambda/functions/builtin/fn1
test/java/com/jnape/palatable/lambda/functions/builtin/fn1 Expand file tree Collapse file tree 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 .Collection ;
6+
7+ public final class Size implements Fn1 <Iterable <?>, Long > {
8+
9+ private static final Size INSTANCE = new Size ();
10+
11+ private Size () {
12+ }
13+
14+ @ Override
15+ public Long apply (Iterable <?> iterable ) {
16+ if (iterable instanceof Collection )
17+ return (long ) ((Collection ) iterable ).size ();
18+
19+ long size = 0L ;
20+ for (Object ignored : iterable ) {
21+ size ++;
22+ }
23+ return size ;
24+ }
25+
26+ public static Size size () {
27+ return INSTANCE ;
28+ }
29+
30+ public static Long size (Iterable <?> iterable ) {
31+ return size ().apply (iterable );
32+ }
33+ }
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 .ArrayList ;
6+ import java .util .Collection ;
7+
8+ import static com .jnape .palatable .lambda .functions .builtin .fn1 .Size .size ;
9+ import static java .util .Arrays .asList ;
10+ import static java .util .Collections .emptyList ;
11+ import static org .junit .Assert .assertEquals ;
12+ import static org .mockito .Mockito .spy ;
13+ import static org .mockito .Mockito .when ;
14+
15+ public class SizeTest {
16+
17+ @ Test
18+ public void countsElementsInIterable () {
19+ assertEquals ((Long ) 0L , size (emptyList ()));
20+ assertEquals ((Long ) 3L , size (asList (1 , 2 , 3 )));
21+ }
22+
23+ @ Test
24+ public void optimizesForCollections () {
25+ Collection <Integer > collection = spy (new ArrayList <Integer >() {{
26+ add (1 );
27+ add (2 );
28+ add (3 );
29+ }});
30+ when (collection .iterator ()).thenThrow (new IllegalStateException ("should not be using the iterator" ));
31+ assertEquals ((Long ) 3L , size (collection ));
32+ }
33+ }
You can’t perform that action at this time.
0 commit comments