How to translate java 8 lambda in java 7?

In Java 8, we have lambdas, like this

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

How to implement this functionality in Java 7?

+4
source share
4 answers

There are two differences between Java 7 and 8 related to this issue.

  • There Listwas no method in Java 7 sort. You should have used Collections.sort.
  • In Java 7, lambda expressions ( ->) were not part of the language.

Java 7 equivalent

Collections.sort(list, new Comparator<Integer>() {
    @Override
    public int compare(Integer v1, Integer v2) {
        // Write what you need here.     
    }
});
+5
source

This basically means:

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

Java 8 introduced the concept of lambda, which eliminates the syntax of an anonymous subclass (among other things). You can read about it here .

+2

, Java 8, Java 7:

a.sort(new Comparator() {
    public int compare(Object v1, Object v2) {
        // ...
    }
}

, v1 v2, Object.

+1

java 8 - . Comparable , compareTo, , , Collections.sort Comparator.

java 8, - . v1 v2. , .

EDIT:

Java 8:

java.util.Random r = new java.util.Random();
ArrayList<TestClass> a = new ArrayList<>();
for( int i = 0; i < 10; i++ ){
    TestClass t = new TestClass();
    t.setValue(r.nextInt());
    a.add(t);
}

System.out.println("Before sort.");
a.sort((v1, v2) -> { return Integer.compare( v1.getValue(), v2.getValue()); });
a.forEach( x -> System.out.println("Value: " + x.getValue()));

( Java 7):

java.util.Random r = new java.util.Random();
ArrayList<TestClass> a = new ArrayList<>();
for( int i = 0; i < 10; i++ ){
    TestClass t = new TestClass();
    t.setValue(r.nextInt());
    a.add(t);
}

System.out.println("Before sort.");
Collections.sort(a, new Comparator<TestClass>(){
    public int compare(TestClass x, TestClass y) {
        return Integer.compare(x.getValue(), y.getValue());
    }

});
for(TestClass x : a){
    System.out.println("Value: " + x.getValue());
}

, - .

0
source

Source: https://habr.com/ru/post/1609318/


All Articles