一個用戶的list列表,一個員工的list列表,現在比較兩個列表中的id是否相同。
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class TestListComponent {
public static void main(String[] args) {
List<User> userList=new ArrayList<>();
for(int i=1;i<=30;i++){
User user=new User();
user.setUserId(i);
user.setName(i+"name");
userList.add(user);
}
List<Employee> employeeList=new ArrayList<>();
for(int i=30;i>=1;i--){
Employee employee=new Employee();
employee.setEmployeeId(i);
employeeList.add(employee);
}
System.out.println("===="+isALLCheckpointHasTime(userList,employeeList));
}
public static boolean isALLCheckpointHasTime(List<User> userList, List<Employee> employeeList){
//將列表中需要比較的對象拿出來
List<Integer> userIntList=userList.stream().map(User::getUserId).collect(Collectors.toList());
List<Integer> employeeIntList= employeeList.stream().map(Employee::getEmployeeId).collect(Collectors.toList());
if(userIntList==employeeIntList){
return true;
}
//遍歷一個對象,查看另外一個list中是否存在
return !userIntList.retainAll(employeeIntList);
}
看一下retainAll的源碼
protected transient int modCount = 0;
transient Object[] elementData;
private int size;
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
//調用自己的私有方法
return batchRemove(c, true);
}
//如果此 collection 由於調用而發生更改,則返回 true
//集合A比較與集合B的交集
private boolean batchRemove(Collection<?> c, boolean complement) {
//獲得當前對象的所有元素
final Object[] elementData = this.elementData;
//w:標記兩個集合公共元素的個數
int r = 0, w = 0;
//設置標誌位
boolean modified = false;
try {
//遍歷集合A
for (; r < size; r++)
//判斷集合B中是否包含集合A中的當前元素
if (c.contains(elementData[r]) == complement)
//如果包含則直接保存。
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
// 如果 c.contains() 拋出異常
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
//w爲當前集合A的length
w += size - r;
}
//如果集合A的大小放生改變
if (w != size) {
// clear to let GC do its work
// 清除工作
for (int i = w; i < size; i++)
elementData[i] = null;
//記錄集合中元素的改變(add/remove)
modCount += size - w;
//設置當前數組的大小
size = w;
//返回爲true
modified = true;
}
}
return modified;
}
}