4/15/2014

Java - SDK 8 New Features

Hi,

This code shows some of the coolest features of the SDK 8.

As you can see functional methods have been added and will facilitate our work.

Yeeeeeaaaaay

 package uk.ac.imperial.cup.main;  
 import java.util.Comparator;  
 import java.util.List;  
 import java.util.ArrayList;  
 import java.util.Optional;  
 public class Main {  

   public static void main(String[] args) {  
     List<People> peoples = populateList();  
     peoples.stream()  //USE OF STREAM, THE SAME AS PIPE IN LINUX|UNIX
         .filter((People p) -> p.getLastName().equals("Stevens")) //FILTER PEOPLE WITH STEVENS AS LAST NAME
         .sorted(Comparator.comparing(People::getFirstName).reversed()) //SORT FILTERED LIST BY FIRST NAME DESC  
         .forEach((People p) -> System.out.println(p.toString()));  //PRINT EACH ELEMENT OF THE SORTED AND FILTERED LIST
    }  

   private static java.util.List<People> populateList() {  
     java.util.List<People> peoples = new ArrayList<People>();  
     peoples.add(new People("Christophe", "Stevens", Optional.ofNullable(28))); //CREATE AN OPTIONAL IN CONSTRUCTOR 
     peoples.add(new People("Vincent", "Stevens", Optional.ofNullable(30)));  
     peoples.add(new People("Kilye", "Minogue", Optional.ofNullable(45)));  
     peoples.add(new People("William", "Adams", Optional.ofNullable(39)));  
     peoples.add(new People("Tom", "Jones", Optional.ofNullable(73)));  
     peoples.add(new People("Ricky", "Wilson", Optional.ofNullable(null)));  
     return peoples;  
   }  
 }  
 class People  
 {  
   private String FirstName, LastName;  
   private Optional<Integer> Age;  //DECLARING AN OPTIONAL
   public People(String firstName, String lastName, Optional<Integer> age) {  
     FirstName = firstName;  
     LastName = lastName;  
     Age = age;  
   }  
   public String getFirstName() {  
     return FirstName;  
   }  
   public void setFirstName(String firstName) {  
     FirstName = firstName;  
   }  
   public String getLastName() {  
     return LastName;  
   }  
   public void setLastName(String lastName) {  
     LastName = lastName;  
   }  
   public Optional<Integer> getAge() {  
     return Age;  
   }  
   public void setAge(Optional<Integer> age) {  
     Age = age;  
   }  
   //TESTING IF OPTIONAL IS PRESENT WITH TERNARY OPERATOR
   @Override  
   public String toString()  
   {  
     return String.format("%s, %s %s", getLastName(), getFirstName(), getAge().isPresent()?getAge().get() + " year":"");  
   }  
 }  

No comments:

Post a comment