比较大型列表并提取丢失的数据

Tec*_*awi 6 java collections list

我有两个非常大ArrayList,每个包含数百万的数据.我想过滤掉List1不存在的数据List2和/或反之亦然.

我已经尝试过Apache CollectionUtils,Java 8流API但没有任何成功.

Java 8并行流消耗所有CPU,而CollectionUtils继续比较没有任何输出的数据集.

POJO样本

public DataVO {
 private String id;
 private String value;
 ...
 // getters / setters

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = (prime * result) + ((id == null) ? 0 : id.hashCode());
  return result;
 }

 @Override
 public boolean equals(final Object obj) {
  ...
  ...
  final DataVO other = (DataVO) obj;
  if (id == null) {
   if (other.id != null) {
    return false;
   }
  }
  else if (!id.equals(other.id)) {
   return false;
  }
  return true;
 }
}
Run Code Online (Sandbox Code Playgroud)

hashCode()/ equals()可以有更多的字段,现在我保持简单.

我也试过List1分成更小的块然后尝试比较List2没有任何结果.我看过其他问题,但没有人考虑过非常大的数量.

如果您有任何指示,请告诉我.

Pas*_*loe 3

您可以将大块读ArrayList入 a HashSet,例如 10k 个元素。确保在HashSet构造函数上设置大小。然后对于每个块HashSet#RemoveAll与另一个块进行调用ArrayList。剩下的条目就是你的答案。甚至可能与ThreadPoolExecutor.

List missing = new ArrayList(); // answer

for (int i = 0; i < list1.size(); ) {
    int offset = i;
    i += 16 * 1024;
    if (i > list1.size()) i = list1.size();
    Set chunk = new HashSet(list1.subList(offset, i));

    for (int j = list2.size(); --j >= 0; chunk.remove(list2.get(j));
    missing.addAll(chunk);
}
Run Code Online (Sandbox Code Playgroud)