Java 8 - Default Methods and Enhanced Stream API


In this post we'll talk about Java 8 default methods and new stream API.First let's go back and talk about how previous Java versions handled interfaces and what are the rules applied.For that we'll implement simple intrface which gives us time details.

public interface TimeClient {
    void setDateAndTime(int day, int month, int year, int hour, int minute, int second);
    LocalDateTime getLocalDateTime();
}

As you can see all the methods are abstract and do not have a method body.Let's implement this interface in a class and add method bodies to the methods.

public class SimpleTimeClient implements TimeClient {

    private LocalDateTime dateAndTime;

    public SimpleTimeClient() {
        dateAndTime = LocalDateTime.now();
   }
   public void setDateAndTime(int day, int month, int year, int hour, int minute, int second) {
        LocalDate dateToSet = LocalDate.of(day, month, year);
        LocalTime timeToSet = LocalTime.of(hour, minute, second);
        dateAndTime = LocalDateTime.of(dateToSet, timeToSet);
   }
   public LocalDateTime getLocalDateTime() {
       return dateAndTime;
   }
   public String toString() {
     return dateAndTime.toString();
   }
   public static void main(String... args) {
        TimeClient myTimeClient = new SimpleTimeClient();
        System.out.println(myTimeClient.toString());
    }
}
When you run this it prints something like follows.(The time you run the application)

2017-02-13T17:47:48.684


Everything is obvious up to now.Now assume that you want to add another method to the TimeClient interface.You need to add the method to the interface and override it on a class in order to add some functionality to it. However rather than leaving the new method abstract and body-less you can add it as a default implementation with a body.So in the TimeClient interface we can do like follows.

void setDateAndTime(int day, int month, int year,int hour, int minute, int second);
    static ZoneId getZoneId (String zoneString) {
        try {
            return ZoneId.of(zoneString);
        } catch (DateTimeException e) {
            System.err.println("Invalid time zone: " + zoneString +
                "; using default time zone instead.");
            return ZoneId.systemDefault();
        }
     default ZonedDateTime getZonedDateTime(String zoneString) {
          return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));     }
 }

As you can see some of the conventions used in earlier Java versions were little bit altered in the new version.Like this you can change the interfaces and methods inside it while ignoring the traditional ways we used earlier.

So you know about default methods and it's time to learn about new Java stream API.Look at the following example.

public class Stream {

    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        Random r = new Random();
        for (int m = 0; m < 10; m++) {
            int a = r.nextInt(10);
            System.out.print(a + " ");
            numbers.add(a);
        }

        int sum = numbers.stream().reduce(Integer::sum).get();
        System.out.println("\n" + sum);
        numbers.stream().filter(num -> {
            return num > 5;
        }).forEach(n -> System.out.print(n + " "));
        System.out.println("");
        numbers.stream().map(num -> num * 2 + 1).forEach(n -> System.out.print(n + " "));
    }
}

As you can see we can reduce several lines of code to single line using new Stream API.We used Stream API in the previous examples also to get the birthdays and print them according to ascending order.I think now you can fully understand about the advantages and the implementation of Stream API.

Comments