我试图通过合并另外两个列表来生成一个 ArrayList。我允许重复对象,但是我生成的 ArrayList 必须包含两个初始列表之间的差异。我意识到这听起来很复杂,所以这里有一个例子:
ArrayList 1: [obj1, obj1, obj1, obj2, obj4, obj4]
ArrayList 2: [obj1, obj2, obj2, obj3]
结果数组列表: [obj1, obj1, obj2, obj3, obj4, obj4]
我觉得这应该很简单,但我似乎无法弄清楚。我会使用 ArrayList1.removeAll(ArrayList2),但是每个对象都有自己的 ID,所以我认为我不会检测到它们是同一个对象。
编辑:修复了我生成的 ArrayList 中的一个错误
谢谢!
最佳答案
简单地使用一个hashmap,将一个元素映射到它在list1中出现的次数,另一个hashmap映射到list2,然后新建一个arraylist并添加objx n次,其中n = abs(hashmap1.get(objx) - hashmap2.get(objx)).
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
List<Integer> list1 = Arrays.asList(new Integer[] { 1, 1, 1, 2, 4, 4 });
List<Integer> list2 = Arrays.asList(new Integer[] { 1, 2, 2, 3 });
HashMap<Integer, Integer> hashMap1 = new HashMap<>();
HashMap<Integer, Integer> hashMap2 = new HashMap<>();
for (Integer i : list1) {
if (hashMap1.containsKey(i)) {
hashMap1.put(i, hashMap1.get(i) + 1);
} else {
hashMap1.put(i, 1);
}
}
for (Integer i : list2) {
if (hashMap2.containsKey(i)) {
hashMap2.put(i, hashMap2.get(i) + 1);
} else {
hashMap2.put(i, 1);
}
}
HashSet<Integer> dedup = new HashSet<>();
for (Integer i : list1) {
dedup.add(i);
}
for (Integer i : list2) {
dedup.add(i);
}
ArrayList<Integer> result = new ArrayList<>();
for (Integer i : dedup) {
Integer n1 = hashMap1.get(i);
Integer n2 = hashMap2.get(i);
int n = Math.abs((n1 == null ? 0 : n1) - (n2 == null ? 0 : n2));
for (int j = 0; j < n; ++j) {
result.add(i);
}
}
for (Integer i : result) {
System.out.println(i);
}
}
}
关于java - 合并两个具有重复项的 Java Arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36285103/