How to apply a condition if all values in a list are equal Java

Asked

Viewed 69 times

2

I have a list of People and I want to know how to know to know if all these objects are equal, Independent of any matricula, userPadrao, business rule, etc...

this snippet is from Controller

@Transacional
@Post("app/mesa2/")
public void gravarUsuarioPadraoSelecionado() {

    String cpfFormatado = request.getParameter("cpfFormatado");
    Long cpf = Long.valueOf(cpfFormatado.replaceAll("\\D", ""));

    Long id = Long.valueOf(request.getParameter("id"));
    CpDao.getInstance().consultaEGravaUsuarioPadrao(id, cpf);
    
    result.redirectTo("/app/mesa2");
}

this part is from dao

public DpPessoa consultaEGravaUsuarioPadrao(long id, long cpf){

    final Query qry = em().createNamedQuery("consultarPessoaAtualPelaInicial");
    qry.setParameter("idPessoaIni", id);
    final DpPessoa pes = (DpPessoa) qry.getResultStream().findFirst().orElse(null);
    
    List<DpPessoa> lista  = obterUsuarioPadrao(cpf);
    
    for(DpPessoa pessoa : lista) {
            pessoa.setUsuarioPadrao(0);
            em().merge(pessoa);
        }
        
     if (pes.getUsuarioPadrao().equals(0)) {
            pes.setUsuarioPadrao(1);
            em().merge(pes);
        }

    return pes;
}

in this section I show the modal if the value is equal to 0

public static boolean exibirModalSelecionarUsuarioPadrao(DpPessoa usuario) {
    return (usuario.getUsuarioPadrao() != null && usuario.getUsuarioPadrao().equals(0));
}

and finally I check in jsp

<c:if test="${exibirModalSelecionarUsuarioPadrao}">
    <script>
        $(document).ready(function() {
            $('#modalEscolhaUsuarioPadrao').modal('show');
        });             
    </script>
</c:if>

Obs: the matriculations in the case would be different functions that a person performs, formerly the person logged into the system with the matriculation instead of Cpf, and as there were people with almost 30 matriculations it ended up being very complicated, the intention is to log into Cpf having a standard registration plate (one that is used more frequently). With the code used as an example I can select and set the default matricula, on the start screen there is a combo where the exchange of the matriculas can be made (this exchange does not make any changes in the bank, only a swap in the selected matricula independent of the value that is in the bank). Only when making this change to the combo the modal is shown again, because the selected matricula has the value equal 0 (since it can only have a matricula as standard). What I want to do is take this list of matricules and check if all are zeroed, pro modal be displayed only once for the user to choose which one will be set as default, because so if I select a combo registration just for consultation and have any other set as default, the modal will no longer be displayed.

  • 1

    Dude, good, I didn’t understand almost anything of the explanation, things like "log in to the license plate" and "Person object with default user field" didn’t become clear to me. I voted to close as unclear. But it seems that in general you need to improve the modeling of your objects, which is a broad subject and can not explain everything in one answer.

  • Registration you are talking about is the user registration in the system? I deduced that this is it. I was thinking of enrollment as something specific to classes/disciplines/schools. And each person has a list of registrations/registrations that comes along when you bring the personal object from the bank? Because it seems to me that the default user should be tied to the enrollment and not to the person, then you would go through the list of enrollments in search of a pattern. Or is each person at the same time a license plate? It’s a bit confusing. If it is, what I see is that it doesn’t make sense for you to check a person’s default user and yes the list.

  • I put an Obs: explaining what I’m trying to do

  • I get it. You have a list of objects and you just want to know how to know if all these objects are equal. No matter license plate, standard user, business rule, nothing. Reduce the question to this specific question then otherwise there will be a question that only suits you and not other users.

  • I’ll do it thank you

  • check should be done before data is saved. not when data is rescued. study the List, Set and Map and Array classes.

Show 1 more comment

2 answers

1

I don’t know if the interface List Java has a way of knowing if all objects are the same, if there will be some method in the interface documentation, but I don’t think there is. And in fact it allows equal objects, either by the criterion of uniqueness of instance (i.e., comparable with ==) or by having the same content (i.e., overriding the methods equals() and hashCode() which are always important to overwrite when you will place objects in collections, and using the equals() to compare the instances instead of ==).

First you need to know that there are these two cited ways of comparing and seeing if it is one of them that you want.

Then you can do it in several ways, one is to go through the list and go checking if the object n is equal to n-1 until a different one is found or reaches the end of the list.

Another way is to throw these items into one Set (set) and see if you have more than one element. This is for the case of using the equals(). In Set the elements do not repeat, they cannot have two equal by the criterion of equals(), insert a similar one replaces the previous one.

Conclusion, if the Set at the end has size 1, it is because it only had one equal element in the list.

A simple way of doing:

Set conjunto = new HashSet(lista);
if (conjunto.size() == 1) { ...

A little more information:

What are the differences between "equals()", "compareTo()", and even "=="?

How to compare Strings in Java?

  • I know it’s like Integer (and I don’t know why not a int) , but there does not need to be this relation 1 to 1 between the types, it may well be a boolean in the object that is mapped to an integer in the database, it is easier to handle in the code, under conditions, etc. The boolean type does not exist in Java for nothing, in your case it makes more sense to wonder if the user is default YES or NO and not one or zero, but since there should not be the boolean type in the database, one can do the mapping (conversion).

0


I solved the problem as follows, went through the list and added a counter, comparing the value of each enrollment.

public static boolean exibirModalSelecionarUsuarioPadrao(DpPessoa pessoa) {
    
    List<DpPessoa> lista = CpDao.getInstance().listarPorCpf(pessoa.getCpfPessoa());
    int contador = 0;
    
    for (DpPessoa usuario : lista) {
        if(usuario.getUsuarioPadrao() == 0) {
            contador++;
        }
    }
    
    if(contador == lista.size()) {
        return true;
    }
    return false;
}

Browser other questions tagged

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