Logo

Programming-Idioms

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

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 = new ArrayList<>();
for (T t : A) if (B.contains(t)) c.add(t);
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 = A.stream().filter(B::contains).toList();
(def c (clojure.set/intersection (set a) (set b)))
using System.Linq;
using System.Collections.Generic;
c = a.Intersect(b).ToList();
C = lists:flatten([A -- B] ++ [B -- A]).
func intersection[S ~[]T, T comparable](a, b S) S {
	s, l := a, b
	if len(b) < len(a) {
		s, l = b, a
	}

	set := make(map[T]struct{}, len(s))
	for _, x := range s {
		set[x] = struct{}{}
	}

	c := make(S, 0, len(s))
	for _, x := range l {
		if _, found := set[x]; found {
			c = append(c, x)
			delete(set, x)
		}
	}
	return c
}
func intersection[S ~[]T, T comparable](a, b S) S {
	seta := make(map[T]bool, len(a))
	for _, x := range a {
		seta[x] = true
	}
	setb := make(map[T]bool, len(b))
	for _, y := range b {
		setb[y] = true
	}

	var c S
	for x := range seta {
		if setb[x] {
			c = append(c, x)
		}
	}
	return c
}
seta := make(map[T]bool, len(a))
for _, x := range a {
	seta[x] = true
}
setb := make(map[T]bool, len(a))
for _, y := range b {
	setb[y] = true
}

var c []T
for x := range seta {
	if setb[x] {
		c = append(c, x)
	}
}
import Data.List (intersect)
a `intersect` b
const c = [...new Set(a)].filter(e => b.includes(e));
$c = array_intersect($a, $b)
uses Classes;
for elem in a do
  if (b.indexof(elem) >= 0) and (c.indexof(elem) = -1) then
    c.add(elem);
my %u;
$u{$_} = 1 for @a, @b;
my @c = keys %u;
c = list(set(a).intersection(b))
c = list(set(a) & set(b))
c = a & b
use std::collections::HashSet;
let set_a: HashSet<_> = a.into_iter().collect();
let set_b: HashSet<_> = b.into_iter().collect();
let c = set_a.intersection(&set_b);
use std::collections::HashSet;
let unique_a = a.iter().collect::<HashSet<_>>();
let unique_b = b.iter().collect::<HashSet<_>>();

let c = unique_a.intersection(&unique_b).collect::<Vec<_>>();

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