SeouliteLab

[Java/자바] BiPredicate의 and() 메소드 활용 예제 본문

프로그래밍

[Java/자바] BiPredicate의 and() 메소드 활용 예제

Seoulite Lab 2024. 3. 13. 08:23

BiPredicate의 and() 메소드란?

BiPredicate 인터페이스에는 두 개의 BiPredicate를 하나로 결합하는 and() 메소드가 있습니다. 이 메소드는 두 BiPredicate가 모두 true를 반환할 때만 true를 반환합니다.

예제 1: 두 숫자가 모두 양수인지 확인하기

import java.util.function.BiPredicate;

BiPredicate<Integer, Integer> isPositive = (a, b) -> a > 0 && b > 0;

BiPredicate<Integer, Integer> bothPositive = isPositive.and(isPositive);

boolean result1 = bothPositive.test(5, 7);
boolean result2 = bothPositive.test(4, -6);

System.out.println("Are both numbers positive? " + result1); // 출력: true
System.out.println("Are both numbers positive? " + result2); // 출력: false

이 예제에서는 and() 메소드를 사용하여 두 숫자가 모두 양수인지 확인합니다.

예제 2: 두 문자열이 모두 "java"를 포함하는지 확인하기

import java.util.function.BiPredicate;

BiPredicate<String, String> containsJava = (str1, str2) -> str1.contains("java") && str2.contains("java");

BiPredicate<String, String> bothContainJava = containsJava.and(containsJava);

boolean result1 = bothContainJava.test("java programming", "python and java");
boolean result2 = bothContainJava.test("python", "java script");

System.out.println("Do both strings contain 'java'? " + result1); // 출력: true
System.out.println("Do both strings contain 'java'? " + result2); // 출력: false

이 예제에서는 and() 메소드를 사용하여 두 문자열이 모두 "java"를 포함하는지 확인합니다.

예제 3: 두 숫자 중 하나가 10 이상이고 다른 하나가 100 이하인지 확인하기

import java.util.function.BiPredicate;

BiPredicate<Integer, Integer> isTenOrMore = (a, b) -> a >= 10 || b >= 10;
BiPredicate<Integer, Integer> isHundredOrLess = (a, b) -> a <= 100 || b <= 100;

BiPredicate<Integer, Integer> tenAndHundred = isTenOrMore.and(isHundredOrLess);

boolean result1 = tenAndHundred.test(5, 120);
boolean result2 = tenAndHundred.test(15, 90);

System.out.println("Is one number 10 or more and the other 100 or less? " + result1); // 출력: false
System.out.println("Is one number 10 or more and the other 100 or less? " + result2); // 출력: true

이 예제에서는 and() 메소드를 사용하여 두 숫자 중 하나가 10 이상이고 다른 하나가 100 이하인지 확인합니다.