Commits

Micha Kops committed c4baa09

Optional/getOrElse examples added.

Comments (0)

Files changed (1)

src/com/hascode/tutorial/Main.java

         persons.stream().sorted((pers1,pers2) -> pers1.getName().compareTo(pers2.getName())).forEach(p -> System.out.println("name: "+p.getName()+", age: "+p.getAge()));
         
         System.out.println("--- optional examples ---");
-        Optional<Person>  person = computePossiblyWithoutResult();
+        Optional<Person>  person = computePossiblyWithoutResult(true);
         if(person.isPresent()){
             System.out.println(person.get().getName());
         }
+        // or better:
+        person.ifPresent(p -> System.out.println(p.getName()));
+        
+        // with fallback
+        Person fallbackPerson = new Person("Max",33);
+        System.out.println(person.orElse(fallbackPerson).getName());
+        person = computePossiblyWithoutResult(false);
+        System.out.println(person.orElse(fallbackPerson).getName());
     }
     
-       private static Optional<Person> computePossiblyWithoutResult() {
-        try {
-            // do something
-            Person p = new Person("Foo",1);
+       private static Optional<Person> computePossiblyWithoutResult(boolean doesWork) {
+        if(doesWork){
+            Person p = new Person("Sam I am",1);
             return Optional.of(p);
-        } catch (Exception e){
-            return Optional.empty();
-        }
+        } 
+            
+        return Optional.empty();
     }
 }