public
Last active

Exploring the new Collection APIs to be introduced in Java 8

  • Download Gist
gistfile1.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
import java.util.*;
public class EnhancedCollections{
public static void main(String[] args){
List<Integer> counts = new ArrayList<Integer>();
for(int i=1;i <= 10; i++){
counts.add(i);
}
//Using external iterators
System.out.println("Using external iterator");
for(Integer i : counts){
System.out.print(i+" ");
}
System.out.println();
//Using internal iterators
System.out.println("Using internal iterator");
counts.forEach(i -> {System.out.print(i*2+" ");});
System.out.println();
//Printing only Even numbers- Using external iterator
System.out.println("Printing Even numbers- Using External iterator");
for ( Integer i : counts){
if ( i % 2 == 0 ){
System.out.print(i+" ");
}
}
System.out.println();
System.out.println("Printing Even numbers- Using Internal iterator");
counts.filter(i -> i%2 == 0)
.forEach(i-> {System.out.print(i+" ");});
System.out.println();
System.out.println("Odd numbers doubled, a new list created-"+
"Using external Iterator");
List<Integer> newCounts = new ArrayList<Integer>();
for(Integer i : counts){
if ( i % 2 != 0 ){
newCounts.add(i*2);
}
}
for(Integer i : newCounts){
System.out.print(i+" ");
}
System.out.println();
System.out.println("Odd numbers doubled, a new list created-"+
"Using internal Iterator");
List<Integer> newCountsNew = new ArrayList<Integer>();
counts.filter(i -> i % 2 != 0)
.map(i -> i*2)
.into(newCountsNew);
newCountsNew.forEach(i -> {System.out.print(i+" ");});
System.out.println();
}
}

@sanaulla123 which build of Java 8 are you using for the above example Mohamed? b82 doesn't seem to have support for it.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.