1
+ package com .baeldung .streams .mapnotnull ;
2
+
3
+ import static org .junit .jupiter .api .Assertions .assertEquals ;
4
+
5
+ import java .util .List ;
6
+ import java .util .Objects ;
7
+ import java .util .Optional ;
8
+ import java .util .stream .Collectors ;
9
+
10
+ import org .junit .jupiter .api .Test ;
11
+
12
+ public class ReturnNotNullElementsFromStreamMapUnitTest {
13
+
14
+ private static final List <String > INPUT = List .of ("f o o" , "a,b,c,d" , "b a r" , "w,x,y,z" , "w,o,w" );
15
+ private static final List <String > EXPECTED = List .of ("a b c d" , "w x y z" , "w o w" );
16
+
17
+ private String commaToSpace (String input ) {
18
+ if (input .contains ("," )) {
19
+ return input .replaceAll ("," , " " );
20
+ } else {
21
+ return null ;
22
+ }
23
+ }
24
+
25
+ @ Test
26
+ void whenUseMapAndFilter_thenGetTheExpectedResult () {
27
+ List <String > result = INPUT .stream ()
28
+ .map (str -> commaToSpace (str ))
29
+ .filter (Objects ::nonNull )
30
+ .collect (Collectors .toList ());
31
+ assertEquals (EXPECTED , result );
32
+ }
33
+
34
+ @ Test
35
+ void whenUseOptional_thenGetTheExpectedResult () {
36
+ //unnecessarily wrapping in Optional, not recommended
37
+ List <String > result = INPUT .stream ()
38
+ .map (str -> Optional .ofNullable (commaToSpace (str )))
39
+ .filter (Optional ::isPresent )
40
+ .map (Optional ::get )
41
+ .collect (Collectors .toList ());
42
+ assertEquals (EXPECTED , result );
43
+ }
44
+
45
+ private Optional <String > commaToSpaceOptional (String input ) {
46
+ if (input .contains ("," )) {
47
+ return Optional .of (input .replaceAll ("," , " " ));
48
+ } else {
49
+ return Optional .empty ();
50
+ }
51
+ }
52
+
53
+ @ Test
54
+ void whenUseMapAndFilterWithOptionalReturnValues_thenGetTheExpectedResult () {
55
+ List <String > result = INPUT .stream ()
56
+ .map (str -> commaToSpaceOptional (str ).orElse (null ))
57
+ .filter (Objects ::nonNull )
58
+ .collect (Collectors .toList ());
59
+ assertEquals (EXPECTED , result );
60
+ }
61
+ }
0 commit comments