Skip to content

Instantly share code, notes, and snippets.

@ybonnel
Created January 8, 2014 14:23
Show Gist options
  • Save ybonnel/8317485 to your computer and use it in GitHub Desktop.
Save ybonnel/8317485 to your computer and use it in GitHub Desktop.
Comparaison of Java 7 and Java 8 style
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.IntStream;
/**
* I tried to compare Java 7 and Java 8 (functional way) syntax on a small problem.
* I Also compare performances just for fun.
*/
public class Exercice6 {
private static final int MAX_MINUTES = 60;
private static final int MAX_HOURS = 24;
/**
* Consider an alarm leds displaying the hours and minutes in 24-hour format.
* Question: What is the maximum value reached by the sum of 4 digits?
*/
private static int java7() {
// Old style
int maxSum = 0;
for (int hour = 0; hour < MAX_HOURS; hour++) { // possible hours
for (int minute = 0; minute < MAX_MINUTES; minute++) { // possible minutes
String display = Integer.toString(hour) + Integer.toString(minute); // generate display
// Calculate sum of digits
int sum = 0;
for (char digit : display.toCharArray()) {
sum += Character.getNumericValue(digit);
}
// Memorize max
if (sum > maxSum) {
maxSum = sum;
}
}
}
return maxSum;
}
private static int java8() {
// New Java8 style
return IntStream.range(0, MAX_HOURS).boxed() // possible hours
.flatMap(hour -> IntStream.range(0, MAX_MINUTES).boxed() // possible minutes
.map(minute -> hour.toString() + minute.toString())) // generate dislays
// Get sum of digits
.map(diplay -> diplay.chars().map(Character::getNumericValue).reduce(0, (n1, n2) -> n1 + n2))
// Find max
.max(Integer::compare)
// Display the result if present.
.get();
}
private static long chrono(Supplier<Integer> algo) {
long startTime = System.nanoTime();
int result = algo.get();
long elapsedTime = System.nanoTime() - startTime;
if (result != 24) {
throw new AssertionError();
}
return elapsedTime;
}
public static void main(String[] args) {
// Warm up
for (int i = 0; i < 10000; i++) {
java7();
java8();
}
long java7Time = 0;
long java8Time = 0;
for (int i = 0; i < 10000; i++) {
java8Time += chrono(Exercice6::java8);
java7Time += chrono(Exercice6::java7);
}
System.out.println("Total time for Java 7 : " + TimeUnit.NANOSECONDS.toMillis(java7Time) + "ms");
System.out.println("Total time for Java 8 : " + TimeUnit.NANOSECONDS.toMillis(java8Time) + "ms");
}
}
Total time for Java 7 : 1001ms
Total time for Java 8 : 3232ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment