Skip to content

Instantly share code, notes, and snippets.

@sanaulla123
Created May 26, 2012 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanaulla123/2794193 to your computer and use it in GitHub Desktop.
Save sanaulla123/2794193 to your computer and use it in GitHub Desktop.
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();
}
}
@qnoid
Copy link

qnoid commented Mar 28, 2013

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment