Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #218 List intersection

Create the list c containing all unique elements that are contained in both lists a and b.
c should not contain any duplicates, even if a and b do.
The order of c doesn't matter.

import static java.util.Set.copyOf;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
Set<T> A = copyOf(a), B = copyOf(b);
List<T> c = A.stream().filter(B::contains).toList();
import static java.util.Set.copyOf;
import java.util.ArrayList;
import java.util.List;
a.retainAll(b);
List<T> c = new ArrayList<>(copyOf(a));
import java.util.List;
import java.util.Set;
a.retainAll(b);
List<T> c = List.copyOf(Set.copyOf(a));
import static java.util.Set.copyOf;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
Set<T> A = copyOf(a), B = copyOf(b);
List<T> c = new ArrayList<>();
for (T t : A) if (B.contains(t)) c.add(t);
(def c (clojure.set/intersection (set a) (set b)))

New implementation...
< >
programming-idioms.org