Method Reference

μ•„λž˜μ™€ 같이 μ‚¬μš©ν•˜λ©° ν•΄λ‹Ή ν΄λž˜μŠ€μ— (μΈμŠ€ν„΄μŠ€) λ©”μ„œλ“œλ₯Ό :: 으둜 λΆ™μ—¬μ„œ μ‚¬μš©ν•œλ‹€.

Class :: (Instance) Method

Method 의 Reference λ₯Ό μ „λ‹¬ν•˜λŠ”λ‹€λŠ” 의미이기 λ•Œλ¬Έμ— Lamda 보닀 μΆ•μ•½λœ 문법이닀.

Java 의 Method λŠ” 일급 객체가 μ•„λ‹ˆκΈ° λ•Œλ¬Έμ— 객체의 Reference λ₯Ό μ „λ‹¬ν•˜λŠ” λ°©μ‹μœΌλ‘œ λ™μž‘λœλ‹€.

Function<String, Integer> func = str -> Integer.parseInt(str);

Function μΈν„°νŽ˜μ΄μŠ€λŠ” ν•˜λ‚˜μ˜ 인자λ₯Ό λ°›μ•„ λ‹€λ₯Ένƒ€μž…μ˜ 리턴 νƒ€μž…μ„ κ°–λŠ” apply() Method λ₯Ό κ°–κ³  μžˆλŠ” ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€μ΄λ‹€.

μœ„ μ½”λ“œλ₯Ό μ•„λž˜μ™€ 같이 Method Reference ν˜•νƒœλ‘œ λ°”κΏ”μ„œ μ‚¬μš© κ°€λŠ₯ν•˜λ‹€.

Function<String, Integer> func = Integer::parseInt;
Integer result = f.apply("123");

λ˜ν•œ μ•„λž˜μ™€ 같이 선언적 코딩을 ν†΅ν•˜μ—¬ κ°„λž΅ν™” ν•  수 μžˆλ‹€.

Function<String, Boolean> func = String::isEmpty;
Boolean result = func.apply("123");

isEmpty() λŠ” static method λŠ” μ•„λ‹ˆμ§€λ§Œ 인자둜 λ†ˆμ–΄μ˜€λŠ” νƒ€μž…μ΄ String 이기 λ•Œλ¬Έμ— ν•΄λ‹Ή νƒ€μž…μ˜ λ©”μ„œλ“œλ₯Ό ν˜ΈμΆœν•΄μ€€λ‹€.

λ ˆνΌλŸ°μŠ€λ³„ νƒ€μž… μΆ”λ‘  (Type Inference) 방법

  • Static Method Reference
Function<String, Integer> func = Integer::parseInt;
Integer result = func.apply("123");
  • Instance Method Reference
Function<String, Boolean> func = String::isEmpty;
Boolean result = func.apply("123");
  • Constructor Method Reference

μƒμ„±μžλ„ λ©”μ„œλ“œ 레퍼런슀둜 μž‘μ„± κ°€λŠ₯ν•˜λ‹€.

Supplier λŠ” 인자 없이 return 만 ν•˜λŠ” λ©”μ„œλ“œλ₯Ό 가지고 있으며 λ©”μ„œλ“œ ν˜ΈμΆœμ‹œ new 둜 μƒμ„±λœ String 객체λ₯Ό λ¦¬ν„΄ν•œλ‹€.
μ΄λŠ” λ¬Όλ‘  κΈ°λ³Έ μƒμ„±μžλ₯Ό ν˜ΈμΆœν•˜κ²Œ λœλ‹€.

Supplier<String> str = String::new;
  • λ°”κΉ₯ μΈμŠ€ν„΄μŠ€ λ©”μ„œλ“œ 레퍼런슀
String str = "Hello";
Predicate<String> pre = str::equals;
pre.test("world");
Comparator<String> compare = String::compareTo;

자주 μ‚¬μš©ν•˜λŠ” ν•¨μˆ˜ν˜• μΈν„°νŽ˜μ΄μŠ€

Functional Interface Parameter Type Return Type Abstract Method Description Other Method
Runnable μ—†μŒ void run μΈμžλ‚˜ λ°˜ν™˜ κ°’ 없이 μ•‘μ…˜μ„ μˆ˜ν–‰ν•œλ‹€. μ—†μŒ
Supplier μ—†μŒ T get T νƒ€μž… 값을 κ³΅κΈ‰ν•œλ‹€.
Consumer T void accept T νƒ€μž… 값을 μ†ŒλΉ„ν•œλ‹€.
BiConsumer<T, U> T, U void accept T와 Uνƒ€μž… 값을 μ†ŒλΉ„ν•œλ‹€. andThen
Function<T, R> T, R apply T νƒ€μž… 인자λ₯Ό λ°›λŠ” ν•¨μˆ˜λ‹€. compose
andThen
identity
BiFunction<T, U, R> T, U, R apply T와 Uνƒ€μž… 인자λ₯Ό λ°›λŠ” ν•¨μˆ˜λ‹€. andThen
UnaryOperator T T apply T νƒ€μž…μ— μ μš©ν•˜λŠ” 단항 μ—°μ‚°μžλ‹€. compose
andThen
identity
BinaryOperator T, T T apply T νƒ€μž…μ— μ μš©ν•˜λŠ” 이항 μ—°μ‚°μžλ‹€. andThen
maxBy
minBy
Predicate T boolean test Boolean 값을 λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜λ‹€. and
or
negate
isEqual
BiPredicate<T, U> T, U boolean test 두 가지 인자λ₯Ό λ°›κ³  boolean 값을 λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜λ‹€. and
or
negate