How to print only numbers that repeat between two different lists?

Asked

Viewed 109 times

-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: https://repl.it/repls/TragicSiennaBoolean

I need only the repeating numbers between the two lists to be printed, so only:

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

inserir a descrição da imagem aqui

1 answer

0


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

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 don’t want this to happen, create a defensive copy:

List<Long> intersecao = new ArrayList<>(lista1);
intersecao.retainAll(lista2);
  • All right Elipe, is not working on Repl.

  • I got it right here... but like I would with Big Integer???

  • @William the same way. You’d just have to change your List for List<BigInteger> and add the Bigintegers for her.

  • Thanks friend!

  • Hello Felipe Marinho, the only problem is that if the numbers were not in a list, (List) for example, as it would be to do the same system, print only the repeated numbers of two different formulas??

  • "retainAll" does not only work for printed numbers that are not within a list...

  • @William O retainAll is a method of API of Collections. You can apply this operation to any collection that implements it (List, Set, Queue, etc) of any type of element (String, Double, any class). If you have, for example, arrays storing the values, just create any collection from them and run the method. In case you, for some reason, want to do "on the arm", take a look at how this method is implementing in ArrayList here.

  • So Felipe, I posted a new question because I can’t print without the lists...

  • Alright Felipe, I posted another question.. https://answall.com/questions/275985/como-imprimir-apenas-n%C3%Bameros-que-se-repetem-entre-duas-formulas-diferentes

Show 4 more comments

Browser other questions tagged

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