1

I am having lists of String type say list aLista and bListb first list might have at max 10 elements however bListb might have thousand or even more elements. Now i have to find all elements from aList which are not in bListb . Here is my approach

List<String> aLista = Arrays.asList("Anil","Abhishek","Ritu");
List<String> bListb = Arrays.asList("g","o","e","Abhishek","Ritu");

List<String> result3 = aLista.stream().filter(al -> 
!bListb.contains(al)).collect(Collectors.toList());
System.out.println(result3);
// output Anil

But i am not sure about performance as bListb might have much elements later on . So i just came to know about best optimum way of doing this. thanks for your time.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

3 Answers3

3

You may use a set. Contains for a HashSet is O(1) compared to O(n) for a list, therefore you should never use a list if you often need to run contains.

Set<String> bSet = new HashSet<>(bListb);
aLista.stream().filter(a -> !bSet.contains(a)).collect(Collectors.toList());
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
1

If you don't care about the duplicates, then try this:

Set<String> uncommon = new HashSet<>(aLista);
uncommon.removeAll(bListb);
Naman
  • 27,789
  • 26
  • 218
  • 353
ETO
  • 6,970
  • 1
  • 20
  • 37
  • how about `uncommon.removeAll(new HashSet<>(bListb))` ? `bListb` could be huge as OP pointed (might optimise a bit further) ? – Naman Feb 21 '19 at 04:02
  • Yes, it would in most cases. I just thought there is no point to duplicate [this](https://stackoverflow.com/a/27002913/10584605) answer. – ETO Feb 21 '19 at 04:07
0

Since aLista is very limited in size and bListb is potentially huge, you should convert aLista to a Set, not bListb.

Set<String> missing = new HashSet<>(aLista);
for (String s : bListb) {
    if (missing.isEmpty())
        break;
    missing.remove(s);
}

The code will even short-circuit the iteration of bListb if all values have been found, whereas converting bListb to a Set would not allow such short-circuit logic.

Andreas
  • 154,647
  • 11
  • 152
  • 247