Commits

Micha Kops  committed 94b3feb

Optional example added.

  • Participants
  • Parent commits 6769d34

Comments (0)

Files changed (1)

File src/com/hascode/tutorial/Main.java

 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Optional;
 import java.util.function.Predicate;
 import java.util.stream.Collectors;
 
         long amountTeens = persons.parallelStream().filter(teenager).count();
         System.out.println(amountTeens+" teens found");
         
+        System.out.println("--- additional aggregates example ---");
         int min = persons.stream().min((pers1,pers2) -> Integer.compare(pers1.getAge(), pers2.getAge())).get().getAge();
         int max = persons.stream().max((pers1,pers2) -> Integer.compare(pers1.getAge(), pers2.getAge())).get().getAge();
         System.out.println("min age: "+min+", max age: "+max);
         
         System.out.println("--- sorting example ---");
         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();
+        if(person.isPresent()){
+            System.out.println(person.get().getName());
+        }
     }
     
+       private static Optional<Person> computePossiblyWithoutResult() {
+        try {
+            // do something
+            Person p = new Person("Foo",1);
+            return Optional.of(p);
+        } catch (Exception e){
+            return Optional.empty();
+        }
+    }
 }