Stop the loop when it finds a result

1
public Objeto busca(String nome){
    for(Objeto id : MinhaLista){
        if(id.getNome().equals(nome)){
            return null;
        } else {                
            return id;
        }                   
    }
}

This is the code, it is returning the id or null repeatedly. how do I stop the loop when I find the result and only return one result instead of several?

    
asked by anonymous 27.11.2014 / 02:37

1 answer

3

Let's look at your code:

public Objeto busca(String nome){
    for(Objeto id : MinhaLista){
        if(id.getNome().equals(nome)){
            return null;
        } else {                
            return id;
        }                   
    }
}

When it starts to iterate the first element, if the name matches that expected, it returns null , and when it does not match this object returns.

This is not right. It always returns in the first iteration! Also, it only returns the first element if it not is what you are looking for. If it's what you're looking for it will not return anything! This is pointless.

I think what you wanted is this:

public Objeto busca(String nome){
    for(Objeto id : MinhaLista){
        if(id.getNome().equals(nome)){
            // Achou o que queria, retorna.
            return id;
        }                   
    }
    return null; // Tentou todos e não achou nenhum, desiste.
}

As suggested by Felipe Fonseca in a comment, it is worth treating null s and avoiding NullPointerException s:

public Objeto busca(String nome){
    Objects.requireNonNull(nome, "O nome do objeto a buscar deve ser informado.");
    for(Objeto id : MinhaLista){
        if(nome.equals(id.getNome())){
            // Achou o que queria, retorna.
            return id;
        }                   
    }
    return null; // Tentou todos e não achou nenhum, desiste.
}

I'm assuming that MinhaLista does not contain null elements in it because this does not usually make sense. If this occurs, you can add if (id == null) continue; before this other if that is already in the code.

    
27.11.2014 / 02:44