Java
Java String[]에 원하는 문자가 있는지 확인
바리새인
2025. 1. 15. 22:43
Arrays.asList 이용
String[] array = {"apple", "banana", "cherry"};
String valueToCheck = "banana";
boolean isIncluded = Arrays.asList(array).contains(valueToCheck);
if (isIncluded) {
System.out.println(valueToCheck + " is in the array.");
} else {
System.out.println(valueToCheck + " is not in the array.");
}
for문 이용
String[] array = {"apple", "banana", "cherry"};
String valueToCheck = "banana";
boolean isIncluded = false;
for (String s : array) {
if (s.equals(valueToCheck)) {
isIncluded = true;
break;
}
}
if (isIncluded) {
System.out.println(valueToCheck + " is in the array.");
} else {
System.out.println(valueToCheck + " is not in the array.");
}
Arrays.stream 이용
import java.util.Arrays;
String[] array = {"apple", "banana", "cherry"};
String valueToCheck = "banana";
boolean isIncluded = Arrays.stream(array).anyMatch(valueToCheck::equals);
if (isIncluded) {
System.out.println(valueToCheck + " is in the array.");
} else {
System.out.println(valueToCheck + " is not in the array.");
}