在 Java 中,您可以使用Collection
接口的removeAll
方法。
// Create a couple ArrayList objects and populate them
// with some delicious fruits.
Collection firstList = new ArrayList() {{
add("user1");
add("user2");
}};
Collection secondList = new ArrayList() {{
add("user1");
add("user1");
add("user3");
add("user4");
}};
// Show the "before" lists
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);
// Remove all elements in firstList from secondList
secondList.removeAll(firstList);
// Show the "after" list
System.out.println("Result: " + secondList);
上面的代码将产生以下输出:
First List: [user1, user2]
Second List: [user1, user2, user3, user4]
Result: [user3, user4]