goal
java의 메소드-레퍼런스 (Method Reference)를 이해한다.
잠깐 훑어보고 든 생각 .... "굳이?"
쓰는 이유가 람다(lambda)를 조금 더 쉽게 사용하기 위해 사용하고, 명시되는 매개변수
를 줄이기 위해 사용한다는데 .... 굳이라는 생각이 든다. 각설하고 좀 알아보기나 하자;
p.s) 내가 더 많은 코드를 작성해보면 유용함을 느낄 때가 올려나
1 ] 메소드 레퍼런스 (Method-Reference)
람다(lambda)표현식을 더 간단하게 표현하는 방법이다.
- 메소드 래퍼런스로 생성되는 객체는
익명 구현 객체
이다.
- 람다(lambda) 표현식을 사용한
익명 구현 객체
생성과 사용방법
import java.util.function.IntConsumer;
@FunctionalInterface
interface Student {
void getName(String name);
}
public class Note {
public static void main(String[] args) {
Student student = name -> {
System.out.println(name);
};
student.getName("김은철");
}
}
- 메소드 레퍼런스를 이용한
익명 객체
생성과 사용방법
import java.util.function.IntConsumer;
//@FunctionalInterface
interface Student {
void getName(String name);
}
public class Note {
public static void main(String[] args) {
Student student = System.out::println; //lambda에 비해서 매개변수가 줄어든 것을 확인가능
student.getName("김은철");
}
}
[1] 메소드 레퍼런스 형식
ClassName :: MethodName
[2] 메소드 래퍼런스 종류
종류명 | 설명 |
Static 메소드 래퍼런스 | Static method 를 메소드 래퍼런스 로 사용한다. |
Instance 메소드 래퍼런스 | Instance 메소드 레퍼런스의 메소드는 static이 아니고 객체의 메소드를 의미 |
Constructor 메소드 래퍼런스 | Constructo r 메소드 레퍼런스는 Constructor를 생성 |
1. Static 메소드 래퍼런스
- 사용예시 1번
interface Student {
void getName(String text);
}
public class Note {
public static void main(String[] args) {
Student student = Note::printName; // !! Static 메소드의 메소드 레퍼런스 부분 !!
// lambda식인 경우는 아래와 같다.
// Student student = text -> Note.printName(text);
student.getName("김은철");
}
public static void printName(String text) {
System.out.println("학생의 이름은?? -> " + text )
}
}
/*
=================output===============
학생의 이름은?? -> 김은철
=================output===============
*/
- 사용예시 2번
List<String> companies = Arrays.asList("google", "apple", "naver", "daum");
companies.stream().forEach(company -> System.out.println(company)); // [1] lambda expression
companies.stream().forEach(System.out::println); // [2] static method reference
/*
==============output==================
google
apple
naver
daum
----------------------------------------------
google
apple
naver
daum
=================output===============
*/
2. Instance 메소드 래퍼런스
Instance
메소드 래퍼런스의 메소드는 static이 아니고 객체의 메소드를 의미한다.
- ClassName :: MethodName 사용법
import java.util.Arrays;
import java.util.List;
class Company {
String name;
public Company(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
public class Note {
public static void main(String args[]) {
List<Company> companies = Arrays.asList(new Company("google"),
new Company("apple"), new Company("samsung"));
companies.stream()
.forEach(company -> company.printName()); //[1] lambda expression
companies.stream()
.forEach(Company :: printName); //[2] method reference expression
}
}
/*
==============output==================
google
apple
samsung
------------------------------------------
google
apple
samsung
==============output==================
*/
- String::length 사용법
List<String> companies = Arrays.asList("google", "apple", "google", "apple", "samsung");
companies.stream() //stream 생성
.mapToInt(String::length) // 람다식: company -> company.length() && 중개연산
.forEach(System.out::println); // 최종연산
// 실행 결과
// 6
// 5
// 6
// 5
// 7
3. Constructor 메소드 레퍼런스
Cunstructor 메소드 래퍼런스는 Constructor를 생성해주는 코드이다.
- lambda식을 이용한 생성자 호출
public static class Company {
String name;
public Company(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
public static void main(String args[]) {
List<String> companies = Arrays.asList("google", "apple", "google", "apple", "samsung");
companies.stream()
.map(name -> new Company(name))
.forEach(company -> company.printName());
}
// 실행 결과
// google
// apple
// google
// apple
// samsung
- 메소드 래퍼런스를 이용한 리펙토링
List<String> companies = Arrays.asList("google", "apple", "google", "apple", "samsung");
companies.stream()
.map(Company::new)
.forEach(Company::printName);