Friday, 30 May 2014

ArrayList : forEach

public void forEach(Consumer<? super E> action)
Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

import java.util.*;
import java.util.function.*;

class MyConsumer<T> implements Consumer<T>{
 public void accept(T task){
  System.out.println("Processing Task " + task);
 }
}

import java.util.*;

class ArrayListForEach{
 public static void main(String args[]){
  ArrayList<Integer> myList;
  MyConsumer<Integer> cons;
  
  myList = new ArrayList<> ();
  cons = new MyConsumer<Integer>();
  
  myList.add(1);
  myList.add(2);
  myList.add(3);
  
  myList.forEach(cons);
 }
}

Output
Processing Task 1
Processing Task 2
Processing Task 3

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment