Spring/JAVA

[Java8 Lambda] Using Functional Interfaces (Predicate, Consumer)

alsruds 2023. 10. 12. 01:31
🤹‍♂️Java Brains 강의🤹‍♂️

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

 

🐣 Missions 🐣

☝️ Sort list by last name

✌️ Create a method that prints all elements in the list

👌 Create a method that prints all people that have last name beginning with C

 

🐤 Solution 🐤

· Interface

public class Person {

    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", age=" + age +
                '}';
    }
}

 

· Main

import java.util.Arrays;
import java.util.Collections;
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),
              new Person("Thomas", "Carlyle", 51),
              new Person("Charlotte", "Bronte", 45),
              new Person("Matthew", "Arnold", 39)
        );

        // Step 1 : Sort list by last name
        Collections.sort(people, (p1, p2) -> p1.getLastName().compareTo(p2.getLastName()));

        // Step 2 : Create a method that prints all elements in the list
        System.out.println("Printing all persons");
        printConditionally(people, p -> true, p -> System.out.println(p));

        // Step 3 : Create a method that prints all people that have last name beginning with C
        System.out.println("Printing all persons with last name beginning with C");
        printConditionally(people, p -> p.getLastName().startsWith("C"), p -> System.out.println(p));
    }

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

출력 값

Predicate<T> : Represents a predicate (boolean-valued function) of one argument

Consumer<T> : Represents an operation that accepts a single input argument and returns no result