Java过滤:一个新集合往老集合中插入,过滤出老集合中没有的元素
import java.util.ArrayList; import java.util.List; import static java.util.stream.Collectors.toList; public class DemoStream { // 新插入的集合元素(newlist)中,如果老的集合元素(oldlist)中有,就不插入进去,过滤出oldlist没有的元素 public static void main(String[] args) { List<User> oldList = new ArrayList<>(); User user1 = new User("1", "张三1"); User user2 = new User("2", "张三2"); User user3 = new User("3", "张三3"); User user4 = new User("4", "张三3"); oldList.add(user1); oldList.add(user2); oldList.add(user3); oldList.add(user4); List<User> newList = new ArrayList<>(); User user5 = new User("1", "张三1"); User user6 = new User("6", "张三6"); User user7 = new User("7", "张三7"); User user8 = new User("8", "张三8"); newList.add(user5); newList.add(user6); newList.add(user7); newList.add(user8); System.out.println("===========过滤出老集合中没有的所有元素==========="); List<User> resultList = newList.stream().filter(item -> !oldList.parallelStream().map(User::getId).collect(toList()).contains(item.getId()) ).collect(toList()); resultList.forEach(m1 -> { System.out.println(m1); }); } } class User { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", name='" + name + '\'' + '}'; } public User(String id, String name) { this.id = id; this.name = name; } }
结果: