Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - search a string in string array [duplicate]

Tags:

java

arrays

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
   }
like image 405
Hari M Avatar asked Jul 12 '16 16:07

Hari M


People also ask

How do you find duplicates in array of strings in Java?

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.

How do you find a repeated string in an array?

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.

How do you find duplicate values in an array?

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. }


2 Answers

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...)

Example:

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 ... :)
}
like image 94
ΦXocę 웃 Пepeúpa ツ Avatar answered Oct 04 '22 15:10

ΦXocę 웃 Пepeúpa ツ


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");
    }

}
like image 38
Arthur Noseda Avatar answered Oct 04 '22 17:10

Arthur Noseda