Searching an array of strings

How to perform a word search in an array of type String?

Example:

String[] arreglo = { "David", "StackOverflow", "StackOverflow en español" };
String encuentrame = "StackOverflow";
arreglo.?; //¿qué hacer en este caso?
 1
Author: Angel Angel, 2016-03-04

3 answers

If you use Java 8, the best option is to convert your array to Stream via Arrays#stream and perform the search there. The advantage of this alternative is that it supports primitive data arrays.

An example for your case would be the following:

String[] arreglo = { "David", "StackOverflow", "StackOverflow en español" };
String encuentrame = "David";
String resultado = Arrays.stream(arreglo)
                         .filter(s -> s.equals(encuentrame))
                         .findFirst()
                         .orElse(null);
if (resultado != null) {
    System.out.println("Encontrado");
} else {
    System.out.println("No Encontrado");
}

And if you worked with a primitive like int:

int[] arreglo = { 1, 2, 3};
int encuentrame = 3;
int resultado = Arrays.stream(arreglo)
                      .filter(x -> x == encuentrame)
                      .findFirst()
                      .orElse(-1);
if (resultado != -1) {
    System.out.println("Encontrado");
} else {
    System.out.println("No Encontrado");
}

The great thing about using Streams is that you can use different ways to identify the element, not just using the equals method. For example, you can check if both words are equal regardless of uppercase or lowercase this way:

String[] arreglo = { "David", "StackOverflow", "StackOverflow en español" };
String encuentrame = "dAvId";
String resultado = Arrays.stream(arreglo)
                         .filter(s -> s.equalsIgnoreCase(encuentrame))
                         .findFirst()
                         .orElse(null);
if (resultado != null) {
    System.out.println("Encontrado");
} else {
    System.out.println("No Encontrado");
}

If your array has many elements and you are going to search for data on it constantly, it would be better to convert the array data into a Set (set) implemented by HashSet and then perform the searches always against this structure. Searches against a HashSet tend to be faster because the hashCode of the element is made use of, reducing the search time to O(1) (assuming that there are few collisions). Here is an example:

String[] arreglo = { "David", "StackOverflow", "StackOverflow en español" };
Set<String> conjunto = new HashSet<>(Arrays.asList(arreglo));
if (conjunto.contains(...)) {
}
 5
Author: Paul Vargas, 2016-03-05 21:15:16

As a complement to the answers, there are various ways to search an array of strings, for example the common form:

public static boolean buscaString(String[] miarray, String valor) {
    for(String s: miarray){
        if(s.equals(valor))
            return true;
    }
    return false;
}

Using List :

public static boolean buscaString(String[] miarray, String valor) {
    return Arrays.asList(miarray).contains(valor);
}

As already mentioned, this does not work for arrays of primitive types.

Using Set :

public static boolean buscaString(String[] miarray, String valor) {
    Set<String> miSet = new HashSet<String>(Arrays.asList(miarray));
    return miSet.contains(valor);
}
 2
Author: Jorgesys, 2016-03-04 16:31:47

Turning it into a list is the easiest way to write it:

    String[] arrayString = new String[]{"uno", "dos", "tres"};
    String cadenaBuscar = "tres";
    if(Arrays.asList(arrayString).contains(cadenaBuscar)) {
        System.out.println("Encontrado");
    } else {
        System.out.println("No encontrado");
    }

This not only works with String, it also works with any other type of object (as long as you have correctly implemented equals and hashCode). It does not work with primitive type arrays.

 1
Author: Pablo, 2016-03-04 09:21:00