Find String in Arraylist

Asked

Viewed 1,613 times

3

ArrayList<String> posicoes = new ArrayList<String>();

posicoes.add("Ricardo;01051509912;gmail");
posicoes.add("Renato;123456789123;hotmail");
posicoes.add("Rodrigo;09873923121;yahoo");

I have a ArrayList whose name is posicoes and I need to make a search in it that returns me the position (index) of String.

For example:

Localizar: 01051509912 // Retorno: posicoes[0]
Localizar: 123456789123 // Retorno: posicoes[1]

1 answer

5


You have to scan the whole list. You can do it in several ways, the most basic is with a for. And in each item you should check whether to string contains the other string who is seeking.

import java.util.*;

class Main {
    public static void main (String[] args) {
            ArrayList<String> posicoes = new ArrayList<String>();
            posicoes.add("Ricardo;01051509912;gmail");
            posicoes.add("Renato;123456789123;hotmail");
            posicoes.add("Rodrigo;09873923121;yahoo");
            System.out.println(BuscaString(posicoes, "01051509912"));
            System.out.println(BuscaString(posicoes, "123456789123"));
    }
    public static int BuscaString(ArrayList<String> lista, String busca) {
        for (int i = 0; i < lista.size(); i++) if (lista.get(i).contains(busca)) return i;
        return -1;
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Documentation.

I used -1 to indicate that you have not found what you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.