[JAVA] Item 42: Prefer lambdas to anonymous classes

42. You should choose a lambda expression from the anonymous class

package tryAny.effectiveJava;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class AnonymouseVsLambda {
    public static void main(String[] args) {
        List<String> words1 = Arrays.asList("apple", "pen", "pineapple");
        //Write in an anonymous class.
        Collections.sort(words1, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return Integer.compare(s1.length(), s2.length());
            }
        });
        System.out.println(words1);

        //If the type is Raw, a compile error will occur.
        List<String> words2 = Arrays.asList("banana", "grape", "melon");
        //Write in a lambda expression.
        Collections.sort(words2, (s1, s2) -> Integer.compare(s1.length(), s2.length()));
        System.out.println(words2);
    }
}

Recommended Posts

Item 42: Prefer lambdas to anonymous classes
Item 43: Prefer method references to lambdas
Item 23: Prefer class hierarchies to tagged classes
Item 28: Prefer lists to arrays
Item 65: Prefer interfaces to reflection
Item 39: Prefer annotations to naming patterns
Item 85: Prefer alternatives to Java serialization
Item 58: Prefer for-each loops to traditional for loops
Item 61: Prefer primitive types to boxed primitives
Item 81: Prefer concurrency utilities to wait and notify
Item 80: Prefer executors, tasks, and streams to threads
Item 89: For instance control, prefer enum types to readResolve
Item 47: Prefer Collection to Stream as a return type
[Java] About anonymous classes