How to print only numbers that are repeated between two different lists? [duplicate]

-1

I have two lists of 50 numbers. One has multiples of 3 and the other multiples of 7 .

Code:

public static void main(String[] args) {

List<Long> lista1  = new ArrayList<>();
List <Long> lista2 = new ArrayList<>();

for (long a = 1; a <= 50; a++) {

long b,c; 
b = a*3;
c = a*7;      

  lista1.add(b);
  lista2.add(c); 

      }
    System.out.println("Lista(1)="+lista1);
    System.out.println("Lista(2)="+lista2);
  }
}

See working on repl: link

I need only the numbers that repeat between the two lists to be printed, thus only:

List (3) = [21, 42, 63, 84, 105, 126, 147]

    
asked by anonymous 13.02.2018 / 00:07

1 answer

0

Use the retainAll(Collection<?> c) method:

public class RetainsAll {
    public static void main(String[] args) {
        List<Long> lista1 = new ArrayList<>();
        List<Long> lista2 = new ArrayList<>();

        for (long a = 1; a <= 50; a++) {    
            lista1.add(a*3);
            lista2.add(a*7);
        }
        System.out.println("Lista(1) = "+lista1);
        System.out.println("Lista(2) = "+lista2);

        lista1.retainAll(lista2);

        System.out.println("Interseção = " + lista1);
    }
}

Note: This method will change your list. If you do not want this to happen, create a defensive copy:

List<Long> intersecao = new ArrayList<>(lista1);
intersecao.retainAll(lista2);
    
13.02.2018 / 00:20