November 6, 2020 When dealing with arrays in Java, I had a hard time searching for values from the elements of the array, so I will summarize them.
There is a way to use the contains method when searching for a specific value in an array.
You need to import hava.util.Arrays
to use the contains method. Enter the value you want to search in the argument of contains, and if it exists, it will be true and the process within the condition will be passed.
Search for numbers
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Integer num[] = {10, 20, 30};
//Whether the array contains 30
if(Arrays.asList(num).contains(30)) {
System.out.println("Value exists");
}
}
}
Execution result
Value exists
Search for strings
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String bar[] = {"aa", "bb", "cc"};
//Whether the array contains aa
if(Arrays.asList(bar).contains("aa")) {
System.out.println("Value exists");
}
}
}
Execution result
Value exists
You need to import java.util.ArrayList
. The basic writing style is the same as an array.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> num = new ArrayList<Integer>();
num.add(10);
num.add(20);
num.add(30);
if(num.contains(10)) {
System.out.println("Value exists");
}
}
}
[Java] Summary of how to search array and List values with contains method Judge a specific value! How to use Java contains method [for beginners]
Recommended Posts