-
Java 특정 값 배열에 포함 여부 (String, int)Java 2023. 8. 11. 20:24
Arrays.asList()
- java.util.Arrays를 사용
- 기본형 데이터 타입은 작동하지 않는 단점이 있다.
- 기본형 데이터 타입은 Ints.asList() 혹은 Java 8 Stream을 사용해 확인
import java.util.Arrays; public class Main { public static void main(String[] args) { String[] strArr = {"B", "A", "C", "D", "E"}; String strValue = "A"; System.out.println(Arrays.asList(strArr).contains(strValue)); // true } }Ints.asList()
import com.google.common.primitives.Ints; public class Main { public static void main(String[] args) { int[] intArr = {4, 3, 6, 8, 5}; int intValue = 6; System.out.println(Ints.asList(intArr).contains(intValue)); // true } }Java 8 Stream을 이용한 방법
import java.util.Arrays; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { int[] intArr = {5, 3, 4, 7, 6, 8}; int intValue = 4; boolean isExist = Arrays.stream(intArr) .boxed() .collect(Collectors.toSet()) .contains(intValue); System.out.println(isExist); // true } }HashSet을 이용한 사용법
import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { String[] strArr = {"B", "A", "C", "D", "E"}; String strValue = "A"; Set<String> set = new HashSet<>(Arrays.asList(strArr)); System.out.println(set.contains(strValue)); // true } }* 다른 방법 (참고)
Apache Commons Lang 라이브러리
import org.apache.commons.lang3.ArrayUtils; public class Main { public static void main(String[] args) { String[] strArr = {"B", "A", "C", "D", "E"}; String strValue = "A"; System.out.println(ArrayUtils.contains(strArr, strValue)); // true } }Stream.anyMatch()
- String과 int의 사용법이 다르기 때문에 유의하자.
import java.util.Arrays; public class Main { public static void main(String[] args) { // String String[] strArr = {"B", "A", "C", "D", "E"}; String strValue = "A"; System.out.println(Arrays.stream(strArr).anyMatch(strValue::equals)); // true // int int[] intArr = {5, 3, 2, 6, 3, 7}; int intValue = 2; System.out.println(Arrays.stream(intArr).anyMatch(i -> i == intValue)); // true } }Stream.filter() 사용
- 배열을 스트림으로 전환한 다음에 필터링 합니다.
- int형 배열은 == 비교연산자를 사용
- count() 메서드는 return 값이 Long이다.
- 필요하다면 int형으로 변환해서 사용하자.
- 무작정 형변환을 하면 cannot be dereferenced 에러를 확인할 수 있다.
- int는 값 자체이고, 포인터라는 개념이 없어서 포인터 연산 할 수 없기 때문에 intValue() 메서드를 이용할 수 없다.
- cannot be dereferenced 에러 해결 방법
- Long.valueOf()를 이용하여 Long instance로 변환하여 cast합니다.
- ex) int intTypeValue = Long.valueOf(longTypeValue).intValue();
import java.util.Arrays; import java.util.Optional; public class Main { public static<T> long containsCount(T[] values, T target) { return Arrays.asList(values).stream() .filter(x -> x.equals(target)) .count(); } public static<T> boolean strContains(T[] values, T target) { /* 또 다른 사용법 - 개수가 0 이상이면 존재한다. return Arrays.asList(values).stream() .filter(x -> x.equals(target)) .count() > 0; */ return Arrays.asList(values).stream() .filter(x -> x.equals(target)) .findFirst() .isPresent(); } public static boolean intContains(int[] values, int target) { return Arrays.stream(values) .filter(x -> x == target) .count() > 0; } public static void main(String[] args) { String[] strArr = {"B", "A", "C", "A", "E"}; String strValue = "A"; int[] intArr = {5, 3, 4, 7, 6, 8}; int intValue = 4; boolean isExistStr = strContains(strArr, strValue); boolean isExistInt = intContains(intArr, intValue); long existCount = containsCount(strArr, strValue); /* Long to int 형 변환 int existCount = Long.valueOf(containsCount(strArr, strValue)).intValue(); */ System.out.println("String exist : " + isExistStr); // true System.out.println("int exist : " + isExistInt); // true System.out.println("String exist count : " + existCount); // 2 } }출처)
https://www.techiedelight.com/ko/check-array-contains-particular-value-java/
'Java' 카테고리의 다른 글
자바 예외 종류 및 Exception 처리 (0) 2023.08.13 자바 생성자(Constructor) 정리 (0) 2023.08.11 Java 제네릭(Generic) 정리(3)_generic의 extends, super, wildcard (0) 2023.08.11 Java 제네릭(Generic) 정리(2)_static을 이용한 Generic (0) 2023.08.11 Java 제네릭(Generic) 정리(1) (0) 2023.08.11