Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translate java 8's lambda to java 7? [duplicate]

In Java 8 we have lambdas like this one

a.sort((v1, v2) -> {});

How would this functionality be implemented in Java 7?

like image 204
kodaek98 Avatar asked Feb 08 '23 22:02

kodaek98


2 Answers

There are 2 differences between Java 7 and 8 relevant to this question.

  1. In Java 7, List did not have a sort method. You had to use Collections.sort.
  2. In Java 7, lambda expressions ( -> ) were not part of the language.

The Java 7 equivalent is

Collections.sort(list, new Comparator<Integer>() {
    @Override
    public int compare(Integer v1, Integer v2) {
        // Write what you need here.     
    }
});
like image 62
Paul Boddington Avatar answered Feb 11 '23 14:02

Paul Boddington


It basically translates to this:

a.sort(new Comparator<T>(){
    public int compare(T v1, T v2){
        return 0;
    }
});

Java 8 introduced the "lambda" concept which allows you to eliminate the anonymous subclass syntax (among other things). You can read more about it here.

like image 33
Chris Thompson Avatar answered Feb 11 '23 14:02

Chris Thompson