IT/JAVA
[JAVA] 자바 기초 복습 (Chapter.14) part2
j8970
2025. 3. 5. 14:25
📅 학습 기간: 2월 3주차!
🎯 학습 내용: 람다 표현식에서 메서드 참조 (::
연산자) 활용
📌 1. 메서드 참조 (::
연산자)란?
💡 람다 표현식을 더 간결하게 작성할 수 있도록 지원하는 문법
- 단순히 메서드 호출만 하는 경우 람다 표현식보다 간결하게 표현 가능
ClassName::staticMethod
또는instance::instanceMethod
형태로 사용
✅ 1) 정적 메서드 참조 (Static Method Reference)
- 객체 생성 없이 바로 사용할 수 있는 메서드 참조
- 구문:
ClassName::staticMethod
class StaticMethodRef {
static int doubleValue(int x) {
return x * 2;
}
}
public class Main {
public static void main(String[] args) {
// 1) 람다 표현식 사용
Function<Integer, Integer> doubleLambda = x -> StaticMethodRef.doubleValue(x);
// 2) 메서드 참조 사용
Function<Integer, Integer> doubleLambdaRef = StaticMethodRef::doubleValue;
System.out.println(doubleLambda.apply(5)); // 10
System.out.println(doubleLambdaRef.apply(10)); // 20
}
}
✅ 2) 인스턴스 메서드 참조 (Instance Method Reference)
- 객체를 반드시 생성해야 하는 메서드를 참조하는 방식
- 구문:
instance::instanceMethod
public class Main {
public static void main(String[] args) {
String hello = "Hello";
// 1) 람다 표현식 사용
Supplier<String> toUpperLambda = () -> hello.toUpperCase();
// 2) 메서드 참조 사용
Supplier<String> toUpperLambdaRef = hello::toUpperCase;
System.out.println(toUpperLambda.get()); // HELLO
System.out.println(toUpperLambdaRef.get()); // HELLO
}
}
✅ 3) 생성자 참조 (Constructor Reference)
- 새로운 객체를 만들 때 사용하는 참조 방식
- 구문:
ClassName::new
class Person {
private String name;
public Person() {
this.name = "이름 미상";
}
public Person(String name) {
this.name = name;
}
public String getName() { return name; }
}
public class Main {
public static void main(String[] args) {
// 1) 람다 표현식 사용
Supplier<Person> personLambda = () -> new Person("전창현");
// 2) 메서드 참조 사용 (매개변수가 없는 생성자만 사용 가능)
Supplier<Person> personLambdaRef = Person::new;
Person p1 = personLambda.get();
Person p2 = personLambdaRef.get();
System.out.println(p1.getName()); // 전창현
System.out.println(p2.getName()); // 이름 미상
}
}
✅ 4) 임의 객체의 인스턴스 메서드 참조
- 특정 객체가 아닌 여러 객체에 공통된 인스턴스 메서드를 사용할 때 사용
- 구문:
ClassName::instanceMethod
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<String, Integer> stringLengthLambda = str -> str.length();
Function<String, Integer> stringLengthMethodRef = String::length;
System.out.println(stringLengthLambda.apply("Lambda")); // 6
System.out.println(stringLengthMethodRef.apply("Method Reference")); // 17
}
}
🎯 소감
📌 간결한 코딩을 위한 람다식을 더 간단하게 하니까 어지러워지네요...
🚀 마무리
이번 장에서는 메서드 참조 (::
연산자)의 개념과 활용법을 학습했다!