Created
May 26, 2012 14:49
-
-
Save sanaulla123/2794193 to your computer and use it in GitHub Desktop.
Exploring the new Collection APIs to be introduced in Java 8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
@sanaulla123 which build of Java 8 are you using for the above example Mohamed? b82 doesn't seem to have support for it.