📑Method Reference는?
- 기존에 이미 선언되어있는 메서드를 지정하고 싶을 때
- :: 오퍼레이터 사용
- 생략이 많기 때문에 사용할 메서드의 매개변수의 타입과 리턴 타입을 미리 숙지해야 함
📒Method Reference의 케이스
- Case1 : ClassName::staticMethodName
클래스의 static method를 지정할 때
- Case2 : objectName::instanceMethodName
선언 된 객체의 instance method를 지정할 때
- Case3 : ClassName::instanceMethodName
객체의 instance method를 지정할 때
- Case4 : ClassName::new
클래스의 constructor를 지정할 때
1. Case 1 & 2
public static int calculate(int x, int y, BiFunction<Integer, Integer, Integer> operator) {
return operator.apply(x, y);
}
public static int multiply(int x, int y) {
return x * y;
}
public int subtract(int x, int y) {
return x - y;
}
public void myMethod() {
System.out.println(calculate(10, 3, this::subtract));
}
String str = "hello";
Predicate<String> equalsToHello = str::equals;
System.out.println(equalsToHello.test("world"));
System.out.println(calculate(8, 2, (x, y) -> x + y));
System.out.println(calculate(8, 2, Chapter5Section1::multiply));
Chapter5Section1 instance = new Chapter5Section1();
System.out.println(calculate(8, 2, instance::subtract));
instance.myMethod();
2. Case 3
public static void printUserField(List<User> users, Function<User, Object> getter) {
for (User user : users) {
System.out.println(getter.apply(user));
}
}
Function<String, Integer> strLength = String::length;
int length = strLength.apply("hello world");
System.out.println(length);
BiPredicate<String, String> strEquals = String::equals;
System.out.println(strEquals.test("hello", "hello"));
List<User> users = new ArrayList<>();
users.add(new User(3, "Alice"));
users.add(new User(1, "Charlie"));
users.add(new User(5, "Bob"));
printUserField(users, User::getName);
3. Case 4
Map<String, BiFunction<String, String, Car>> carTypeToConstructorMap = new HashMap<>();
carTypeToConstructorMap.put("sedan", Sedan::new);
carTypeToConstructorMap.put("suv", Suv::new);
carTypeToConstructorMap.put("van", Van::new);
BiFunction<Integer, String, User> userCreator = User::new;
User charlie = userCreator.apply(3, "Charlie");
System.out.println(charlie);
String[][] inputs = new String[][] {
{ "sedan", "Sonata", "Hyundai" },
{ "van", "Sienna", "Toyota" },
{ "sedan", "Model S", "Tesla" },
{ "suv", "Sorento", "KIA" }
};
List<Car> cars = new ArrayList<>();
for (int i = 0; i < inputs.length; i++) {
String[] input = inputs[i];
String carType = input[0];
String name = input[1];
String brand = input[2];
cars.add(carTypeToConstructorMap.get(carType).apply(name, brand));
}