Java 8 Default Method Added

 It has been Quite a while since Java 8 released. With the release, they have improved some of the existing APIs and added few new features. One of them is forEach Method in java.lang.Iterable Interface.

Whenever we need to traverse over a collection we have to create an Iterator to iterate over the collection and then we can have our business logic inside a loop for each of the elements inside the collection. We may greeted with ConcurrentModificationException if it is not implemented properly.

The implementation of forEach method in Iterable interface is:

default void forEach(Consumer action) {

        Objects.requireNonNull(action);

        for (T t : this) {

            action.accept(t);

        }

    }


//Program 1 before Java 8

// Java program to demonstrate

// forEach() method of Iterable interface

public class ForEachExample {

public static void main(String[] args)

{

List<String> data = new ArrayList<>();

data.add("New Delhi");

data.add("New York");

data.add("Mumbai");

data.add("London");


Iterator<String> itr = data.iterator();

while (itr.hasNext()) {

System.out.println(itr.next());

// data.remove(itr.next());

// this line can introduce you to

// java.util.ConcurrentModificationException.

}

}

}


Program 2 : After Java8

// Java program to demonstrate

// forEach() method of Iterable interface

public class ForEachExample {

public static void main(String[] args)

{

List<String> data = new ArrayList<>();

data.add("New Delhi");

data.add("New York");

data.add("Mumbai");

data.add("London");

data.forEach(new Consumer<String>() {

@Override

public void accept(String t)

System.out.println(t);

}

});

}

}



Comments

Popular posts from this blog

Java 8 : Find the number starts with 1 from a list of integers

Optional Vs Null Check

How to prevent Singleton Class from Reflection and Serialization