简体   繁体   中英

Merging two Java Arraylists with duplicates

I am attempting to generate an ArrayList by merging two other lists. I am allowed duplicate objects, however my resulting ArrayList must contain the difference between both initial lists. I realize this may sound convoluted, so here is an example:

ArrayList 1: [obj1, obj1, obj1, obj2, obj4, obj4]
ArrayList 2: [obj1, obj2, obj2, obj3]

Resulting ArrayList: [obj1, obj1, obj2, obj3, obj4, obj4]

I feel like this should be simple but I cannot seem to figure it out. I would use ArrayList1.removeAll(ArrayList2), however each object has its' own individual ID so I don't think I would detect that they are the same object.

EDIT: fixed an error in my resulting ArrayList
Thanks!

Simply use a hashmap, mapping an element to the number of times it occurred in list1, and another hashmap for list2, then make a new arraylist and add objx n times, where 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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM