Created
February 25, 2017 09:21
-
-
Save bassemZohdy/ca562254d2edc189e8a2afb8933fc498 to your computer and use it in GitHub Desktop.
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.Arrays; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.util.function.Consumer; | |
import java.util.function.Function; | |
import java.util.function.Predicate; | |
import java.util.function.Supplier; | |
import java.util.stream.IntStream; | |
public class StreamSample { | |
private static final int LIMIT = 4; | |
public static void main(String[] args) { | |
Supplier<Integer> supplier = () -> 5; | |
Consumer<Integer> print = i -> System.out.println("consume " + i); | |
Function<Integer, Integer> multiplyBy5 = i -> i * 5; | |
Predicate<Integer> evenNumbers = i -> i % 2 == 0; | |
Consumer<String> title = s -> System.out.println("\n" + s + "\n" + "---------------------------------"); | |
Integer[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; | |
int count = 0; | |
title.accept("Array For"); | |
for (int i = 0; i < array.length; i++) { | |
int n = array[i]; | |
// Same lines of code | |
n = multiplyBy5.apply(n); | |
if (evenNumbers.test(n)) { | |
print.accept(n); | |
count++; | |
} | |
if (count >= LIMIT) | |
break; | |
////////////////////// | |
} | |
List<Integer> list = Arrays.asList(array); | |
Iterator<Integer> iter = list.iterator(); | |
count = 0; | |
title.accept("Iterator While"); | |
while (iter.hasNext()) { | |
int n = iter.next(); | |
// Same lines of code | |
n = multiplyBy5.apply(n); | |
if (evenNumbers.test(n)) { | |
print.accept(n); | |
count++; | |
} | |
if (count >= LIMIT) | |
break; | |
////////////////////// | |
} | |
count = 0; | |
title.accept("For Each"); | |
for (Integer n : list) { | |
// Same lines of code | |
n = multiplyBy5.apply(n); | |
if (evenNumbers.test(n)) { | |
print.accept(n); | |
count++; | |
} | |
if (count >= LIMIT) | |
break; | |
////////////////////// | |
} | |
title.accept("Java 8 Stream"); | |
IntStream.range(0, 10).boxed().map(multiplyBy5).filter(evenNumbers).limit(LIMIT).forEach(print); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment