Java - 메서드 참조 (::)

c.Hano·2024년 12월 4일

자바

목록 보기
14/17
메서드 참조
메서드 이름을 직접 참조하여 람다 표현식을 간결하게 표현하는 방법.
  • 클래스명::메서드명 or 객체명::메서드명 형태로 작성된다.


클래스명::정적메서드명
import java.util.Arrays;

public class MethodReferenceExample {
    public static void main(String[] args) {
        // 정적 메서드 참조: Integer.parseInt
        String[] numbers = {"1", "2", "3"};
        int[] parsedNumbers = Arrays.stream(numbers)
                                    .mapToInt(Integer::parseInt) // 정적 메서드 참조
                                    .toArray();

        System.out.println(Arrays.toString(parsedNumbers)); // 출력: [1, 2, 3]
    }
}
  • mapToInt // Array 형태를 Int 형태로 바꾼다.
  • Integer::parseInt // e -> Integer.parseInt(e) 를 의미한다.

클래스명::인스턴스메서드명
import java.util.Arrays;

public class MethodReferenceExample {
    public static void main(String[] args) {
        // 인스턴스 메서드 참조: System.out.println
        String[] messages = {"Hello", "World", "!"};

        Arrays.stream(messages).forEach(System.out::println); // 인스턴스 메서드 참조
    }
}
  • System.out::println // e-> System.out.println(e) 를 의미한다.

생성자 참조
import java.util.stream.Stream;

  public class MethodReferenceExample {
    public static void main(String[] args) {
        // 생성자 참조: Person::new
        Stream.of("Alice", "Bob", "Charlie")
              .map(Person::new) // 생성자 참조
              .forEach(System.out::println);
    }
}
class Person {
    private String name;

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

    @Override
    public String toString() {
        return "Person{name='" + name + "'}";
    }
}
  • Person::new // name -> new Person(name) 을 의미한다.
profile
꼬질이

0개의 댓글