More efficient way to compare two variables type List

Asked

Viewed 205 times

0

I have two variables of the type List that need to be compared to each other to verify possible duplicates.

Example of Variable Contents

Variable 01: [01, Test, Active]

Variable 02: [01, Test, Active]

At the moment I’m using the following script in Groovy to check:

for (TransportadoraPostgreSQL transportadorasBDM : transportadorasBanco){
    for(List transportadoraAVerificar : listaTransportadora){
        if (transportadorasBDM.getCodigo().toString().equals(transportadoraAVerificar.get(0).toString())){
            //logger.info("Iguais")
        }
    }
}

But that way when the two variables have, for example, 100 records each, it will be 10,000 checks on Loop, there is some way to be more efficient this verification?

  • That’s right, unless you had some criteria to omit some verification, that’s what you have to do. For example, let’s say that it is guaranteed that the carrier appears only once on the list and you just want to know if there is at least one coincidence need not know how many or which, then it is possible to stop the search for that item when you find the first one, but if there is only zero or one occurrence at all there will be no gain.

  • @bigown And it has as I delete the record repeated, so that when displaying there are no repeated records?

  • If Voce does not want its array to be duplicated and unique, use unique(). for example: def a = [1,2,3,4,5] def b = [1,2,3,4,5, 6] def c = (a + b). Unique()

  • Or Voce can take the difference and add the array, for example: def a = [1,2,3, 4] def b = [1,2,3] def c = a + (b - a) if its "a" is the main array.

1 answer

3

Use Except

var firstNotSecond = list1.Except(list2).ToList();
var secondNotFirst = list2.Except(list1).ToList();

This method is quite fast.

return !firstNotSecond.Any() && !secondNotFirst.Any();

Larger information

  • Is that Groovy? It looks like C#. In addition to this what is being done there internally actually reproduces what his code does, with great chance of lower efficiency, even if small difference. There’s only the optimization I mentioned up there.

Browser other questions tagged

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