[英]Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java
[英]Merging two Java Arraylists with duplicates
我正在嘗試通過合並其他兩個列表來生成ArrayList。 我可以使用重復的對象,但是生成的ArrayList必須包含兩個初始列表之間的差異。 我意識到這聽起來有些麻煩,所以這里有個例子:
ArrayList 1: [obj1,obj1,obj1,obj2,obj4,obj4]
ArrayList 2: [obj1,obj2,obj2,obj3]
結果ArrayList: [obj1,obj1,obj2,obj3,obj4,obj4]
我覺得這應該很簡單,但我似乎無法弄清楚。 我會使用ArrayList1.removeAll(ArrayList2),但是每個對象都有自己的獨立ID,因此我認為我不會檢測到它們是同一對象。
編輯:修復了我得到的ArrayList中的錯誤
謝謝!
只需使用一個哈希圖,將一個元素映射到它在list1中發生的次數,然后將另一個哈希圖映射到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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.