Spring/JAVA

[Java8 Lambda] Method References

alsruds 2023. 10. 18. 01:25
🤹‍♂️Java Brains 강의🤹‍♂️

https://www.youtube.com/playlist?list=PLqq-6Pq4lTTa9YGfyhyW2CqdtW9RtY-I3

 

✨ No input arg. & Calling a method without any args

☑️ () → method()

 

· Examples

public class Main {
    public static void main(String[] args) {

        // no input argument & calling a method without any arguments
        // Thread t = new Thread(() -> printMessage()); -> method execution
        Thread t = new Thread(Main::printMessage);
        t.start();
    }

    public static void printMessage() {
        System.out.println("Hello");
    }
}

➡️ Main::printMessage  ===  () → printMessage

 

✨ One input arg. & Calling a method with that same arg.

☑️ p → method(p)

 

· Examples

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {

        List<Person> people = Arrays.asList(
                new Person("Charles", "Dickens", 60),
                new Person("Lewis", "Carroll", 42)
        );

        System.out.println("Printing all persons");
        // one input argument & calling a method with that same argument
        // perform(people, p -> true, p -> System.out.println(p));
        perform(people, p -> true, System.out::println);
    }

    private static void perform(List<Person> people, Predicate<Person> predicate, Consumer<Person> consumer) {
        for (Person p : people) {
            if (predicate.test(p)) {
                consumer.accept(p);
            }
        }
    }
}

'Spring > JAVA' 카테고리의 다른 글

[Java8 Lambda] Streams  (0) 2023.10.20
[Java8 Lambda] foreach iteration  (0) 2023.10.19
[Java8 Lambda] this  (0) 2023.10.17
[Java8 Lambda] Closures in Lambda Expressions  (1) 2023.10.16
[Java8 Lambda] Exception Handling in Lambdas (try - catch)  (0) 2023.10.13