您可以使用Apache Commons Collections,它有一个明确用于此目的的方法:
public static void main(String[] args) {
List<Integer> a = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
List<Integer> b = Arrays.asList(new Integer[] { 2, 3, 4 });
Collection<Integer> aMinusB = CollectionUtils.subtract(a, b);
System.out.println(aMinusB);
}
打印结果为:[1, 5].
Apache Commons 库经过充分测试,通常用于扩展标准 Java 功能。这个特定的方法接受Iterable 作为参数,所以你可以使用任何你想要的Collection。您还可以混合使用不同的集合类型:
public static void main(String[] args) {
List<Integer> a = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
Set<Integer> b = new HashSet<Integer>(Arrays.asList(new Integer[] { 2, 3, 4 }));
Collection<Integer> aMinusB = CollectionUtils.subtract(a, b);
System.out.println(aMinusB);
}
打印结果是一样的,[1, 5]。
查看 Javadoc here。
为了完整起见,谷歌的Guava库does not have this feature:
Collection *subtract*(Collection, Collection)
没有等价物——创建一个包含 a 的 ArrayList,然后对 b 中的每个元素调用 remove。
但是,它实现了一个名为 Sets.difference() 的方法,如果您更喜欢 Guava 并使用集合,则可以使用该方法:
public static void main(String[] args) {
Set<Integer> a = new HashSet<Integer>(Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }));
Set<Integer> b = new HashSet<Integer>(Arrays.asList(new Integer[] { 2, 3, 4 }));
Set<Integer> aMinusB = Sets.difference(a, b);
System.out.println(aMinusB);
}
结果是a 中不存在于b 中的所有元素(即再次[1, 5])。当然,顺序是不确定的,因为它是在集合上操作的。