1/7/2019 - 7:26 AM

Lambda Expressions in Java (Lecture)


Functional Interfaces, originated from functional programming.

//beautiful lambda expression
List<Student> getStudentsByClass(String klass) {
    return filterStudents((Student s) -> s.klass.equals(klass), allStudents());


(T1 p1, T2 p2, ..., Tn pn) -> {statement}

//types can be ommited
(p1,p2, ..., pn) -> {statement}

//parenthesis can be ommitted for a single parameter
p1 -> {statement}

// curly brackets can be ommitted for a single expression
p1 -> expression
//traditionally searching for something in a list with a foreach loop -> very repetitive
for (Student s : EventoDB.allStudents()){
        if (s.klass.equal(klass) { restult.add(s);}
    return result;

//Avoid repetition by abstracting the test as an interface
interface StudentPredicate { 
    boolean test(Student s);

List<Student> filterStudents(StudentPredicate p, List<Student> students){
    List<Student> result = new ArrayList<>();
    for (Student s : students) {
        if (p.test(s)) { //testing with the intefarce
    return result;

//Implement "class test" as a StudentPredicate
class ClassPredicate implements StudentPredicate { private String klass;
    ClassPredicate(String klass) { this.klass = klass; }
    public boolean test(Student s) {
       return s.klass.equals(klass);
} }

//potential usage
public List<Student> getStudentsByClass(String klass) {
   return filterStudents(
    new ClassPredicate(klass),allStudents());
//given a list of students
class Student {
      final String lastName, firstName, email, klass; Student(String l, String f, String e, String k) {
              this.lastName = l;   this.firstName = f;
     = e;      this.klass = k;

//filling the list with elements
class EventoDB {
  static List<Student> allStudents() {
    List<Student> students = new ArrayList<>();
        students.add(new Student("Cherek", "Oliver","", "1Ibb"));
        students.add(new Student("Andermatt", "Jonathan","", ”1Ic"));
      return students;
public interface Fun<I,O> {
O apply(I i); // This is the single abstract method

Fun<String, Integer> f = s -> s.length();
Integer i = f.apply("Java");

public static void bla(Fun<String, String> ss){

bla(s -> s.toUpperCase());