How to compare two different lists in Java?

Asked

Viewed 3,601 times

4

I have two lists that share a common value between them. I wanted these selected objects to be filtered so that it is added to another list

List<Objeto1> lista1 = new ListaElementos1().getElementos();
List<Objeto2> lista2 = new ListaElementos2().getElementos();

List<Objeto1> destino = new ArrayList<>();



for(Objeto1 item : lista1){
    for(Objeto2 array: lista2){
        if(array.getId() == item.getId()){
            if(!destino.contains(item)){
                destino.add(item);
            }
        }
    }
}

That was the way I found to make the filter so that it met my need. But I don’t think this is the best way to do it (by having to run the two entire lists for each record).

Is there any way to do this without the need to create 2 loops?

  • 1

    The lists are equal?

  • which I will compare not

  • Unless you have some specific requirement that’s not in the question, you don’t have much to do. May have some restriction that could allow some optimization.

  • I thought of that question based on the attribute Find in C#. It accepts a lambda to filter these records and returns an object from the list that meets this filter. I don’t know how it does it in a list, if it’s a for within it or a more optimized way. Perhaps this method is just as efficient but with a high complexity of understanding. About the specific requirement, I get a Json that sends me which group the item belongs to (by id), and the other object is a list of attributes related to that group

2 answers

4

You can do this using stream:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Teste {
    public static void main(String[] args) {
        List<Integer> lista1 = Arrays.asList(1, 2, 3, 4, 5, 6);
        List<String> lista2 = Arrays.asList("5", "6", "7", "8");

        List<Integer> interseccao = lista1.stream().filter(item1 -> {
            return lista2.stream().filter(item2 -> new Integer(item2).equals(item1)).findAny().isPresent();
        }).collect(Collectors.toList());

        System.out.println(interseccao);
    }
}
  • 1

    Note: according to the owner of the question, the lists are different.

  • Different lists: A=[1,2,3,4], B=[1,2,3,4,5,6,54,100000,12,-1]. Do you understand? That is, the amount of elements is different.

  • Here the elements can even be different, which can be easily converted, but the amount of elements are equal. List<Integer> lista1 = Arrays.asList(1, 2, 3, 4, 5, 6);&#xA; List<String> lista2 = Arrays.asList("5", "6", "7", "8", "9", "10");

  • Although the number of elements in the list does not make a difference, I changed in the example the number of elements.

2


Maybe that’s what you want, but either way he’ll run the two lists.

I’m practically beginner in Java and I’m not sure if this is the best way.

            List<Object1> arrayObj1 = Arrays.asList(
                                new Object1(1),
                                new Object1(2),
                                new Object1(3),
                                new Object1(4)
                            );

    List<Object2> arrayObj2 = Arrays.asList(
                                new Object2(4),
                                new Object2(5),
                                new Object2(6),
                                new Object2(7)
                            );

    //Array que receberá o resultado da comparação
    List<Object1> array2Obj1;

    array2Obj1 = arrayObj1.stream()
        .filter( o1 -> {
            return arrayObj2.stream()
                    .map(Object2::getId)
                    //Compara se o id do Object2 é igual ao id do Object1
                    .anyMatch(i2 -> i2.equals(o1.getId()));
        }).collect(Collectors.toList());

   array2Obj1.stream().map(Object1::getId).forEach(System.out::println); // Result: 4
  • 1

    It worked perfectly! Thank you very much!

Browser other questions tagged

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