Java의 선택적 ifPresent()

MD Aminul Islam 2023년10월12일
  1. Java의 선택적 클래스 메서드 ifPresent()
  2. Java에서 ifPresent() 메서드 사용
Java의 선택적 ifPresent()

이 자습서에서는 Java에서 ifPresent()라는 선택적 클래스 메서드에 대해 설명합니다.

Java의 선택적 클래스 메서드 ifPresent()

Optional 클래스 ifPresent()Class 인스턴스에 값이 포함된 경우 작업을 수행하는 데 주로 사용되는 인스턴스 메서드입니다. Consumer 인터페이스의 구현입니다.

이 메서드를 가져오려면 모든 Java 프로그램에서 가장 일반적으로 사용되는 패키지 중 하나인 java.util 패키지를 가져와야 합니다. 클래스 이름은 선택입니다.

이제 이 방법의 몇 가지 예를 살펴보겠습니다.

Java에서 ifPresent() 메서드 사용

ifPresent() 메서드의 작동 방식을 이해하기 위해 먼저 비어 있는 Optional을 입력한 다음 결과의 변경 사항을 추적할 수 있도록 Optional에 값을 입력합니다.

다음 스니펫은 ifPresent() 메서드의 예를 보여줍니다. 이 예에서는 소비자를 비워 둡니다.

코드 예:

// Importing necessary packages
import java.util.Optional;
import java.util.function.Consumer;

class Main {
  public static void main(String args[]) {
    Consumer<String> MyConsumer =
        value -> System.out.println("\tConsumer Called: [" + value + "]"); // Declaring a Consumer.
    Optional<String> MyOptional = Optional.empty(); // Declaring a Optional
    MyOptional.ifPresent(MyConsumer); // Checking whether the Optional is empty or not.
  }
}

먼저 Consumer를 선언한 다음 Optional을 생성하고 Optional.empty()를 사용하여 빈 상태로 설정합니다. 위의 코드를 실행하면 Optional이 비어 있으므로 출력이 표시되지 않습니다.

이제 Optional에 값을 입력하겠습니다.

코드 예:

// Importing necessary packages
import java.util.Optional;
import java.util.function.Consumer;

public class Main {
  public static void main(String args[]) {
    Consumer<String> MyConsumer =
        value -> System.out.println("\tConsumer Called: [" + value + "]"); // Declaring a Consumer.
    Optional<String> MyOptional = Optional.of("This is a value."); // Declaring a Optional
    MyOptional.ifPresent(MyConsumer); // Checking whether the Optional is empty or not.
  }
}

여기에서 문자열 값을 Optional로 설정합니다. 업데이트된 코드를 실행하면 아래 출력이 표시됩니다.

출력:

Consumer Called: [This is a value.]
MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

관련 문장 - Java Method