11package com .baeldung .stream ;
22
3+ import java .util .ArrayList ;
34import java .util .List ;
45import java .util .stream .Collectors ;
56import java .util .stream .IntStream ;
67
78import com .codepoetics .protonpack .Indexed ;
89import com .codepoetics .protonpack .StreamUtils ;
910
11+ import io .vavr .Tuple2 ;
12+ import io .vavr .collection .Stream ;
13+ import one .util .streamex .EntryStream ;
14+
1015public class StreamIndices {
1116
1217 public static List <String > getEvenIndexedStrings (String [] names ) {
13- List <String > evenIndexedNames = IntStream .range (0 , names .length )
14- .filter (i -> i % 2 == 0 ).mapToObj (i -> names [i ])
18+ List <String > evenIndexedNames = IntStream
19+ .range (0 , names .length )
20+ .filter (i -> i % 2 == 0 )
21+ .mapToObj (i -> names [i ])
1522 .collect (Collectors .toList ());
1623 return evenIndexedNames ;
1724 }
1825
26+ public List <String > getEvenIndexedStringsVersionTwo (List <String > names ) {
27+ List <String > evenIndexedNames = EntryStream
28+ .of (names )
29+ .filterKeyValue ((index , name ) -> index % 2 == 0 )
30+ .values ()
31+ .toList ();
32+ return evenIndexedNames ;
33+ }
34+
1935 public static List <Indexed <String >> getEvenIndexedStrings (List <String > names ) {
20- List <Indexed <String >> list = StreamUtils .zipWithIndex (names .stream ())
21- .filter (i -> i .getIndex () % 2 == 0 ).collect (Collectors .toList ());
36+ List <Indexed <String >> list = StreamUtils
37+ .zipWithIndex (names .stream ())
38+ .filter (i -> i .getIndex () % 2 == 0 )
39+ .collect (Collectors .toList ());
2240 return list ;
2341 }
2442
2543 public static List <Indexed <String >> getOddIndexedStrings (List <String > names ) {
26- List <Indexed <String >> list = StreamUtils .zipWithIndex (names .stream ())
27- .filter (i -> i .getIndex () % 2 == 1 ).collect (Collectors .toList ());
44+ List <Indexed <String >> list = StreamUtils
45+ .zipWithIndex (names .stream ())
46+ .filter (i -> i .getIndex () % 2 == 1 )
47+ .collect (Collectors .toList ());
2848 return list ;
2949 }
3050
3151 public static List <String > getOddIndexedStrings (String [] names ) {
32- List <String > oddIndexedNames = IntStream .range (0 , names .length )
33- .filter (i -> i % 2 == 1 ).mapToObj (i -> names [i ])
52+ List <String > oddIndexedNames = IntStream
53+ .range (0 , names .length )
54+ .filter (i -> i % 2 == 1 )
55+ .mapToObj (i -> names [i ])
3456 .collect (Collectors .toList ());
3557 return oddIndexedNames ;
3658 }
59+
60+ public static List <String > getOddIndexedStringsVersionTwo (String [] names ) {
61+ List <Tuple2 <String , Integer >> tuples = Stream
62+ .of (names )
63+ .zipWithIndex ()
64+ .filter (tuple -> tuple ._2 % 2 == 1 )
65+ .toJavaList ();
66+ List <String > oddIndexedNames = new ArrayList <String >();
67+ tuples .forEach (tuple -> {
68+ oddIndexedNames .add (tuple ._1 );
69+ });
70+ return oddIndexedNames ;
71+ }
3772}
0 commit comments