본문 바로가기

명사 美 비격식 (무리 중에서) 아주 뛰어난[눈에 띄는] 사람[것]

JAVA

java.util.function패키지: java.lang.Runnable Supplier<T> Consumer<T> Function<T, R> Predicate<T>

java.util.function패키지

일반적으로 자주쓰이는 형식의 메서드를 함수형 인터페이스로 정의해논 패키지.

https://standout.tistory.com/1433

 

하나의 추상 메서드를 갖는, 함수형 인터페이스

함수형 인터페이스 자바8부터 도입된 기능, 딱 하나의 추상 메서드를 갖는 인터페이스. 예를 들어 Runnable도 run 메서드만을 가지고있어 함수형 인터페이스. Runnable myRunnable = () -> { System.out.println("R

standout.tistory.com

 

함수형 인터페이스의 종류는 아래와 같다.

 

java.lang.Runnable
`Runnable`은 매개변수를 받지 않고 어떤 작업을 수행하는 인터페이스
주로 스레드를 생성하고 실행할 때 사용

// Runnable을 이용한 간단한 스레드 실행
public class Main {
    public static void main(String[] args) {
        // Runnable 객체 생성
        Runnable task = () -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Hello from thread: " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        // Runnable 객체를 이용하여 새로운 스레드 생성 및 실행
        Thread thread = new Thread(task);
        thread.start();

        System.out.println("Main thread exiting...");
    }
}

[출력결과]
Main thread exiting...
Hello from thread: Thread-0
Hello from thread: Thread-0
Hello from thread: Thread-0
Hello from thread: Thread-0
Hello from thread: Thread-0

 

 

 

Supplier<T>
`Supplier`는 매개변수를 받지 않고 값을 제공하는 인터페이스
`get()` 메서드를 호출하여 값을 제공
일반적으로 초기화된 객체를 생성하거나, 계산된 값을 제공

import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) {
        // Supplier를 이용하여 문자열을 제공하는 예시
        Supplier<String> supplier = () -> "Hello, World!";

        // Supplier로부터 값을 얻어와 출력
        String result = supplier.get();
        System.out.println(result);
    }
}

[출력결과]
Hello, World!

 

 

 

Consumer<T>
`Consumer`는 값을 받아들이고 그 값을 소비하는 인터페이스
`accept(T t)` 메서드를 호출하여 값을 소비
주로 데이터를 처리하거나 출력하는 데 사용

import java.util.function.Consumer;

public class Main {
    public static void main(String[] args) {
        // Consumer를 이용하여 문자열을 출력하는 예시
        Consumer<String> consumer = str -> System.out.println("Consumed: " + str);

        // Consumer에 문자열을 전달하여 소비
        consumer.accept("Hello, World!");
    }
}

[출력결과]
Consumed: Hello, World!

 

 

 


Function<T, R>
`Function`은 하나의 입력값을 받아서 다른 타입의 결과값을 반환
`apply(T t)` 메서드를 호출하여 입력값을 받고 결과값을 반환
주로 데이터 변환이나 매핑에 사용

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        // Function을 이용하여 문자열을 정수로 변환하는 예시
        Function<String, Integer> parser = Integer::parseInt;

        // Function에 문자열을 전달하여 변환된 결과를 받음
        int result = parser.apply("123");
        System.out.println("Parsed integer: " + result);
    }
}

[출력결과]
Parsed integer: 123

 

 

 

Predicate<T>

Function의 변형, 반환값이 boolean이라는 것만 다르다.
`Predicate`는 주어진 조건에 대한 판별을 수행
`test(T t)` 메서드를 호출하여 조건을 평가하고, 그 결과를 boolean 값으로 반환
주로 조건을 검사하거나 필터링하는 데 사용

import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        // Predicate를 이용하여 숫자가 짝수인지 확인하는 예시
        Predicate<Integer> isEven = num -> num % 2 == 0;

        // Predicate에 숫자를 전달하여 짝수 여부를 확인
        int number = 10;
        if (isEven.test(number)) {
            System.out.println(number + " is even.");
        } else {
            System.out.println(number + " is odd.");
        }
    }
}

[출력결과]
10 is even.