Last active
August 29, 2015 13:57
-
-
Save dnorton/9785997 to your computer and use it in GitHub Desktop.
Just playing around with lambdas
This file contains hidden or 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
package org.dnorton.java8.example; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
/** | |
* Created with IntelliJ IDEA. | |
*/ | |
public class LambdaTest { | |
public static void main(String[] args) { | |
List<Workout> workouts = new ArrayList<Workout>(); | |
workouts.add(new Workout(10, 60,"run")); | |
workouts.add(new Workout(3, 19, "run")); | |
workouts.add(new Workout(30, 120, "bike")); | |
workouts.add(new Workout(2, 61, "swim")); | |
workouts.forEach(System.out::println); | |
workouts.stream().sorted((w1, w2) -> | |
Integer.compare(w1.distance, w2.distance)).forEach(System.out::println); | |
System.exit(0); | |
Workout[] workoutArray = workouts.toArray(new Workout[workouts.size()]); | |
// use lambda in place of Comparator implementation | |
// sort by distance | |
Arrays.sort(workoutArray, (w1, w2) -> | |
Integer.compare(w1.distance, w2.distance) | |
); | |
for (Workout workout: workoutArray) | |
System.out.println(workout); | |
// sort by duration | |
Arrays.sort(workoutArray, (w1, w2) -> | |
Integer.compare(w1.duration, w2.duration)); | |
for (Workout workout: workoutArray) | |
System.out.println(workout); | |
} | |
} | |
class Workout { | |
Workout(Integer distance, Integer duration, String type) { | |
this.distance = distance; | |
this.duration = duration; | |
this.type = type; | |
} | |
Integer distance; | |
Integer duration; | |
String type; | |
@Override | |
public String toString() { | |
return "Workout type: " + this.type + " distance: " + this.distance + " duration: " + this.duration; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment