In java do we have any method to find that a particular string is part of string array. I can do in a loop which I would like to avoid.
e.g.
String [] array = {"AA","BB","CC" };
string x = "BB"
I would like a
if (some condition to tell whether x is part of array) {
do something
} else {
do something else
}
One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.
Step to find duplicate in String[] Array : Get length of String Arrays using length property of Arrays. Similarly get size of Set/HashSet object using size() method. Finally compare Arrays length with Set size using if-else statement.
function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = 0; j < myArray. length; j++) { if (i != j) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } } return false; // means there are no duplicate values. }
Do something like:
Arrays.asList(array).contains(x);
since that return true if the String x is present in the array (now converted into a list...)
if(Arrays.asList(myArray).contains(x)){
// is present ... :)
}
since Java8 there is a way using streams to find that:
boolean found = Arrays.stream(myArray).anyMatch(x::equals);
if(found){
// is present ... :)
}
You could also use the commons-lang library from Apache which provides the much appreciated method contains
.
import org.apache.commons.lang.ArrayUtils;
public class CommonsLangContainsDemo {
public static void execute(String[] strings, String searchString) {
if (ArrayUtils.contains(strings, searchString)) {
System.out.println("contains.");
} else {
System.out.println("does not contain.");
}
}
public static void main(String[] args) {
execute(new String[] { "AA","BB","CC" }, "BB");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With