[TIL] 2024-07-25

성장일기·2024년 7월 26일

회고

목록 보기
13/37

중요 학습 내용 [JAVA]

Lambda

목적

  • 코드의 간결함

Functional Interface

Consumer

  • 매개변수는 있으나, 반환값이 없다.

Supplier

  • 매개변수는 없으나, 반환값은 있다.

Function

  • 매개변수와 반환값을 매핑한다.

Operator

  • 매개변수와 반환값이 존재하며, 배개변수와 반환값이 동일한 타입이다.

Predicate

  • 매개변수가 있으며, boolean 타입으로 리턴한다.

Method Reference

  • 정적 메소드 참조
    • 클래스 명을 사용하여 정적 메서드 참조
import java.util.function.Function;

public class MethodReferenceExample {
    public static void main(String[] args) {
        // Integer 클래스의 parseInt 정적 메소드를 참조
        Function<String, Integer> stringToInteger = Integer::parseInt;

        Integer result = stringToInteger.apply("123");
        System.out.println(result); // 123 출력
    }
}
  • 인스턴스 메소드 참조 (타입의 특정 객체 메소드 참조)
    • 해당 타입에서 호출되는 인스턴스 메소드 참조
    • 특정 객체를 지정하지 않는다.
    • 파라미터의 타입을 지정한다.
import java.util.function.BiFunction;

public class MethodReferenceExample {
    public static void main(String[] args) {
        BiFunction<String, String, Boolean> lambdaEquals = (s1, s2) -> s1.equals(s2);

        // String 클래스의 인스턴스 메소드 equals를 참조
        BiFunction<String, String, Boolean> methodRefEquals = String::equals;

        System.out.println(lambdaEquals.apply("test", "test")); // true 출력
        System.out.println(methodRefEquals.apply("test", "test")); // true 출력
    }
}
  • 특정 객체의 인스턴스 메소드 참조
    • 이미 존재하는 특정 객체의 메소드를 참조
import java.util.function.Consumer;
import java.util.Arrays;
import java.util.List;

public class MethodReferenceExample {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("one", "two", "three");

        // System.out의 println 인스턴스 메소드를 참조
        Consumer<String> methodRefConsumer = System.out::println;
        list.forEach(methodRefConsumer);
    }
}
  • 생성자 참조
    • 생성자를 참조하여 새로운 객체 생성(new 연산자 사용)
import java.util.function.Function;

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public class MethodReferenceExample {
    public static void main(String[] args) {
        // Person 클래스의 생성자를 참조
        Function<String, Person> constructorRef = Person::new;

        Person person = constructorRef.apply("John");
        System.out.println(person.getName()); // John 출력
    }
}

헷갈린 점

Static & final과 singleton

  • singleton: 처음 생성된 instance가 더이상 생성되지 않는다.
  • static: static 영역에 생성된 instance를 (여러 스레드가) 공유한다.
  • final: 한 번 초기화 된(할당받은) 변수는 더 이상 덮어쓰이지 않는다.
profile
엔지니어로의 성장일지

0개의 댓글