Skip to content

Instantly share code, notes, and snippets.

@sadedv
Created January 13, 2016 08:58
Show Gist options
  • Save sadedv/fc452984a0b02ca83970 to your computer and use it in GitHub Desktop.
Save sadedv/fc452984a0b02ca83970 to your computer and use it in GitHub Desktop.
Java 8 Lambda Example
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.ToIntFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.lang.System.out;
public class FunctionalJava {
private List<Integer> list = new ArrayList<>();
public FunctionalJava() {
createList();
}
public static void main(String[] args) {
FunctionalJava fj = new FunctionalJava();
fj.doTimedCall(FunctionalJava::viaFor);
fj.doTimedCall(FunctionalJava::viaSum);
fj.doTimedCall(FunctionalJava::viaReduce);
// Inlined lambda. This is simply duplicating the functionality of viaSum()
fj.doTimedCall(func -> fj.list
.stream()
.mapToInt(Integer::intValue)
.filter(value -> value > 0)
.sum());
}
public void doTimedCall(ToIntFunction<FunctionalJava> func) {
long startTime = System.currentTimeMillis();
// Here is where the magic happens.
int sum = func.applyAsInt(this);
long endTime = System.currentTimeMillis();
out.println(sum + ". Took " + (endTime - startTime) + "ms");
}
public int viaFor() {
int sum = 0;
for (int i : list) {
sum += i;
}
return sum;
}
public int viaSum() {
return list.stream()
.mapToInt(Integer::intValue)
.sum();
}
public int viaReduce() {
return list.stream()
.mapToInt(Integer::intValue)
.reduce(0, (a, b) -> a + b);
}
private void createList() {
Random random = new Random();
IntStream intStream = random.ints(-100, 100);
list = intStream
.limit(10000)
.boxed()
.collect(Collectors.toList());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment