11package com .baeldung .java8 .optional ;
22
3- import static org . junit . Assert . assertEquals ;
4- import static org . junit . Assert . assertFalse ;
5- import static org .junit .Assert . assertTrue ;
3+ import com . baeldung . optional . Modem ;
4+ import com . baeldung . optional . Person ;
5+ import org .junit .Test ;
66
77import java .util .Arrays ;
88import java .util .List ;
99import java .util .NoSuchElementException ;
1010import java .util .Optional ;
1111
12- import org .junit .Test ;
13-
14- import com .baeldung .java_8_features .Person ;
12+ import static org .junit .Assert .*;
1513
1614public class OptionalTest {
1715 // creating Optional
@@ -95,7 +93,40 @@ public void whenOptionalFilterWorks_thenCorrect() {
9593 boolean is2017 = yearOptional .filter (y -> y == 2017 ).isPresent ();
9694 assertFalse (is2017 );
9795 }
96+ @ Test
97+ public void whenFiltersWithoutOptional_thenCorrect () {
98+ assertTrue (priceIsInRange1 (new Modem (10.0 )));
99+ assertFalse (priceIsInRange1 (new Modem (9.9 )));
100+ assertFalse (priceIsInRange1 (new Modem (null )));
101+ assertFalse (priceIsInRange1 (new Modem (15.5 )));
102+ assertFalse (priceIsInRange1 (null ));
103+
104+ }
98105
106+ @ Test
107+ public void whenFiltersWithOptional_thenCorrect () {
108+ assertTrue (priceIsInRange2 (new Modem (10.0 )));
109+ assertFalse (priceIsInRange2 (new Modem (9.9 )));
110+ assertFalse (priceIsInRange2 (new Modem (null )));
111+ assertFalse (priceIsInRange2 (new Modem (15.5 )));
112+ assertFalse (priceIsInRange1 (null ));
113+ }
114+
115+ public boolean priceIsInRange1 (Modem modem ) {
116+ boolean isInRange = false ;
117+ if (modem != null && modem .getPrice () != null && (modem .getPrice () >= 10 && modem .getPrice () <= 15 )) {
118+ isInRange = true ;
119+ }
120+ return isInRange ;
121+ }
122+
123+ public boolean priceIsInRange2 (Modem modem2 ) {
124+ return Optional .ofNullable (modem2 )
125+ .map (Modem ::getPrice )
126+ .filter (p -> p >= 10 )
127+ .filter (p -> p <= 15 )
128+ .isPresent ();
129+ }
99130 // Transforming Value With map()
100131 @ Test
101132 public void givenOptional_whenMapWorks_thenCorrect () {
@@ -203,4 +234,4 @@ public String getMyDefault() {
203234 System .out .println ("Getting default value..." );
204235 return "Default Value" ;
205236 }
206- }
237+ }
0 commit comments