42. 익명 클래스보다는 람다를 사용하라.

무한성장개발자·2025년 9월 25일

package me.whiteship.chapter07.item42.anonymous_class;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        List<String> words = new ArrayList<>(Arrays.asList("aaa", "bbbbb", "c"));
        System.out.println(words);

        Collections.sort(words, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return Integer.compare(s1.length(), s2.length());
            }
        });

        System.out.println(words);
    }
}

재정의할 객체가 하나인 경우 함수객체라고 한다. 해당 함수 객체를 함수형 인터페이스와 람다를 사용가능하다.

package me.whiteship.chapter07.item42.funcational_interface;

import java.util.*;

import static java.util.Comparator.comparingInt;

public class Main {

    public static void main(String[] args) {
        List<String> words = new ArrayList<>(Arrays.asList("aaa", "bbbbb", "c"));
        System.out.println(words);

        Collections.sort(words, (s1, s2) -> Integer.compare(s1.length(), s2.length()));

//        Collections.sort(words, comparingInt(String::length));
//
//        words.sort(comparingInt(String::length));

        System.out.println(words);
    }
}

인터페이스를 구현할 클래스나 인스턴스가 구현해야 될 게 딱 하나인 경우에는 함수형 인터페이스라고 볼 수가 있다.

package me.whiteship.chapter07.item42.funcational_interface;

import java.util.*;

import static java.util.Comparator.comparingInt;

public class Main {

    public static void main(String[] args) {
        List<String> words = new ArrayList<>(Arrays.asList("aaa", "bbbbb", "c"));
        System.out.println(words);

//        Collections.sort(words, (s1, s2) -> Integer.compare(s1.length(), s2.length()));

        Collections.sort(words, comparingInt(String::length));
//
//        words.sort(comparingInt(String::length));

        System.out.println(words);
    }
}

package me.whiteship.chapter07.item42.funcational_interface;

import java.util.*;

import static java.util.Comparator.comparingInt;

public class Main {

    public static void main(String[] args) {
        List<String> words = new ArrayList<>(Arrays.asList("aaa", "bbbbb", "c"));
        System.out.println(words);

//        Collections.sort(words, (s1, s2) -> Integer.compare(s1.length(), s2.length()));

//        Collections.sort(words, comparingInt(String::length));

        words.sort(comparingInt(String::length));

        System.out.println(words);
    }
}
package me.whiteship.chapter07.item42.operation_before;

import java.util.function.DoubleBinaryOperator;

// 코드 42-4 함수 객체(람다)를 인스턴스 필드에 저장해 상수별 동작을 구현한 열거 타입 (256-257쪽)
public enum Operation {
    PLUS  ("+") {
        @Override
        public double apply(double x, double y) {
            return x + y;
        }
    },
    MINUS ("-") {
        @Override
        public double apply(double x, double y) {
            return x - y;
        }
    },
    TIMES ("*") {
        @Override
        public double apply(double x, double y) {
            return x * y;
        }
    },
    DIVIDE("/") {
        @Override
        public double apply(double x, double y) {
            return x / y;
        }
    };

    private final String symbol;

    Operation(String symbol) {
        this.symbol = symbol;
    }

    @Override public String toString() { return symbol; }

    public abstract double apply(double x, double y);

    // 아이템 34의 메인 메서드 (215쪽)
    public static void main(String[] args) {
        double x = 10;
        double y = 5;
        for (Operation op : Operation.values())
            System.out.printf("%f %s %f = %f%n",
                    x, op, y, op.apply(x, y));
    }
}

이전 코드

package me.whiteship.chapter07.item42.operation_after;

import java.util.function.DoubleBinaryOperator;

// 코드 42-4 함수 객체(람다)를 인스턴스 필드에 저장해 상수별 동작을 구현한 열거 타입 (256-257쪽)
public enum Operation {
    PLUS  ("+", (x, y) -> x + y),
    MINUS ("-", (x, y) -> x - y),
    TIMES ("*", (x, y) -> x * y),
    DIVIDE("/", (x, y) -> x / y);

    private final String symbol;
    private final DoubleBinaryOperator op;

    Operation(String symbol, DoubleBinaryOperator op) {
        this.symbol = symbol;
        this.op = op;
    }

    @Override public String toString() { return symbol; }

    public double apply(double x, double y) {
        return op.applyAsDouble(x, y);
    }

    // 아이템 34의 메인 메서드 (215쪽)
    public static void main(String[] args) {
        double x = 10;
        double y = 5;
        for (Operation op : Operation.values())
            System.out.printf("%f %s %f = %f%n",
                    x, op, y, op.apply(x, y));
    }
}

이후 코드

package me.whiteship.chapter07.item42.anonymous_class;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        List<String> words = new ArrayList<>(Arrays.asList("aaa", "bbbbb", "c"));
        System.out.println(words);

        Collections.sort(words, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
//                this => new Comparator
                return Integer.compare(s1.length(), s2.length());
            }
        });

        System.out.println(words);
    }
}

this는 new Comparator를 의미

package me.whiteship.chapter07.item42.funcational_interface;

import java.util.*;

import static java.util.Comparator.comparingInt;

public class Main {

    public static void main(String[] args) {
        List<String> words = new ArrayList<>(Arrays.asList("aaa", "bbbbb", "c"));
        System.out.println(words);

        Collections.sort(words, (s1, s2) -> {
            //this -> 람다에 바깥에 있는 Main을 가리킨다.
            return Integer.compare(s1.length(), s2.length());
        });

//        Collections.sort(words, comparingInt(String::length));
//
//        words.sort(comparingInt(String::length));

        System.out.println(words);
    }
}

this인 경우 해당 객체를 감싸고 있는 Main class를 의미한다.
여기서는 static이라 컴파일 오류가 나오기는 한다.

0개의 댓글