Exploring the new Collection APIs to be introduced in Java 8
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
@sanaulla123 which build of Java 8 are you using for the above example Mohamed? b82 doesn't seem to have support for it.