1. contains
2. indexOf
3. Stream API
1. contains()
사용법 :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListValueCheck {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("Hello", "Hi"));
// 포함 여부 체크
boolean isContainsHello = list.contains("Hello");
boolean isContainsBye = list.contains("Bye");
// 결과 출력
System.out.println(isContainsHello); // true
System.out.println(isContainsBye); // false
}
}
2. indexOf()
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListValueCheck {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("Hello", "Hi"));
// Hello 포함 여부 체크
int helloIndex = list.indexOf("Hello");
System.out.println("Hello Index : " + helloIndex); // 0
if (helloIndex >= 0) {
System.out.println("Hello는 List에 포함된 문자열입니다."); // printed
}
// Bye 포함 여부 체크
int byeIndex = list.indexOf("Bye");
System.out.println("Bye Index : " + byeIndex); // -1
if (byeIndex >= 0) {
System.out.println("Bye는 List에 포함된 문자열입니다."); // not printed
}
}
}
3. Stream API
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListValueCheck {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("Hello", "Hi"));
// Hello 포함 여부 체크
long count = list.stream().filter(str -> "Hello".equals(str)).count();
System.out.println("Count : " + count);
if (count > 0) {
System.out.println("Hello는 리스트에 포함된 문자열입니다.");
}
}
}
'개발공부 > Java 문법' 카테고리의 다른 글
[Java] 맵 (Map) (0) | 2022.02.04 |
---|