Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. package com.java8.foreach;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. import java.util.function.Consumer;
  7. import java.lang.Integer;
  8.  
  9. public class Java8ForEachExample {
  10.  
  11. public static void main(String[] args) {
  12.  
  13. //creating sample Collection
  14. List<Integer> myList = new ArrayList<Integer>();
  15. for(int i=0; i<10; i++) myList.add(i);
  16.  
  17. //traversing using Iterator
  18. Iterator<Integer> it = myList.iterator();
  19. while(it.hasNext()){
  20. Integer i = it.next();
  21. System.out.println("Iterator Value::"+i);
  22. }
  23.  
  24. //traversing through forEach method of Iterable with anonymous class
  25. myList.forEach(new Consumer<Integer>() {
  26.  
  27. public void accept(Integer t) {
  28. System.out.println("forEach anonymous class Value::"+t);
  29. }
  30.  
  31. });
  32.  
  33. //traversing with Consumer interface implementation
  34. MyConsumer action = new MyConsumer();
  35. myList.forEach(action);
  36.  
  37. }
  38.  
  39. }
  40.  
  41. //Consumer implementation that can be reused
  42. class MyConsumer implements Consumer<Integer>{
  43.  
  44. public void accept(Integer t) {
  45. System.out.println("Consumer impl Value::"+t);
  46. }
  47.  
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement