comparing a variable with a vector or list

0

Usually to perform a conditional using a vector or a list and it is necessary to perform a for and perform the if line by line in this way.

//sendo item uma string e listaItens um List<String>
for(String lista: listaItens){
    if(item.equal(lista){
       return true;
    }
}

I would like to know if there is a more effective way to perform this operation where the if itself already compares with the whole list without the need for for example if(variavel.equal(lista.asItem) or something of the genre.

    
asked by anonymous 02.03.2018 / 15:59

2 answers

2

Has the contains method, which belongs to the ArrayList class. Here's a basic example of what you want:

ArrayList<String> lista = new ArrayList<>();
  lista.add("Ola");
  lista.add("Mundo");
  String mundo = "Mundo";
if (lista.contains(mundo)) {
  System.out.println("Achou!");
}

Now, to speak with precision if this implementation is more effective than the other one, I think not, because if it is a search in a list, all the items in the list will be traversed.

    
02.03.2018 / 16:11
-1

Try using the lambda expression (function without declaration) in the forEach function

List<String> list = Arrays.asList("1", "2d", "sf3", "fgfd4", "fgdf5", "6", "7");


list.forEach(n -> System.out.println(n.equals("sf3")?"achou":""));
    
02.03.2018 / 16:16