Created
May 11, 2018 06:21
-
-
Save ThangLeQuoc/e18a8e11a860074071badc19e69bcce3 to your computer and use it in GitHub Desktop.
Java 8 - Lambda Expresison
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.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.function.Function; | |
import java.util.function.Predicate; | |
//www . ja va 2 s .c om | |
public class Main { | |
public static void main(String[] args) { | |
List<Student> employees = Arrays.asList( | |
new Student(1, 3, "John"), | |
new Student(2, 3, "Jane"), | |
new Student(3, 4, "Jack") | |
); | |
// with predicate | |
System.out.println(findStudents(employees, createCustomPredicateWith(10_000))); | |
// with function definition, both are same | |
Function<Double, Predicate<Student>> customFunction = threshold -> (e -> e.gpa > threshold); | |
System.out.println(findStudents(employees, customFunction.apply(10_000D))); | |
} | |
private static Predicate<Student> createCustomPredicateWith(double threshold) { | |
return e -> e.gpa > threshold; | |
} | |
private static List<Student> findStudents(List<Student> employees, Predicate<Student> condition) { | |
List<Student> result = new ArrayList<>(); | |
for (Student e : employees) { | |
if (condition.test(e)) { | |
result.add(e); | |
} | |
} | |
return result; | |
} | |
} | |
class Student { | |
public int id; | |
public long gpa; | |
public String name; | |
Student(int id, long g, String name) { | |
this.id = id; | |
this.gpa = g; | |
this.name = name; | |
} | |
@Override | |
public String toString() { | |
return id + ">" + name + ": " + gpa; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment