comparing a variable with a vector or list

Asked

Viewed 273 times

0

Usually to perform a conditional using an array or a list and need 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 carry out this operation where the property if already makes the comparison with the entire list without the need for the for example if(variavel.equal(lista.asItem) or something like that.

  • What do you want with this code? Find only an equal value or all that are equal?

  • only find an equal, need to know if the variable has the value equal to one of the elements of the list, if yes I am obliged to use this value, if not I have to ignore the value contained in the variable.

2 answers

2


It has the contains method, which belongs to the Arraylist class. Follow 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, speak precisely if this implementation is more effective than the other, I think not, because when it comes to searching in a list will always be covered all the items in the list.

  • In fact it is List.contains.

  • I expressed myself badly, but I improved the answer a little!

-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":""));
  • This works with string?

  • I tested with string and it worked List<String> list = Arrays.asList("1", "2d", "sf3", "fgfd4", "fgdf5", "6", "7"); list.foreach(n -> System.out.println(n. equals("sf3")));

  • The idea was to remove the noose and get a boolean of this (see the return true in OP code). All you did was make a loop with a lambda, but it remains a loop and does not provide a boolean.

Browser other questions tagged

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