Find String in ArrayList

2
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 search it to return the position (index) of String .

For example:

Localizar: 01051509912 // Retorno: posicoes[0]
Localizar: 123456789123 // Retorno: posicoes[1]
    
asked by anonymous 30.08.2017 / 05:23

1 answer

3

You have to scan the entire list. You can do it in many ways, the most basic one is with for . And on each item you should check if the string contains the other string you are looking for.

import java.util.*;

class Ideone {
    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;
    }
}

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

Documentation .

I used -1 to indicate that you did not find what you want.

    
30.08.2017 / 05:46