Search code examples
javaarraylistsetarray-mergeno-duplicates

How do I add non-existing values in from arrayList2 to arrayList1?


Let's say I have an arrayList1 of Points. The data structure is like this :

(1,2)->(2,2)->(3,2)->(4,2)->(5,2)

I have another arrayList2 of Points :

(2,2)->(1,2)->(8,5)->(9,3)

How do I compare the two lists and add non-existing values from arrayList2 to arrayList1?

current solution

The only method I can think of now is using a for loop to compare each of the Points in arrayList1 such as, if(!arrayList1.contains(arrayList2.get(i))){ arrayList1.add(arrayList2.get(i)); } i++;.

Is there a more efficient way or already prepared method from a class? Because I have arrayList1 until arrayList6 to compare and replace....


Solution

    1. For one-liner lovers (running demo):

      List<Point> list3 = new ArrayList<Point>(new HashSet<Point>(list1){{ addAll(list2); }});
      
    2. Safe version * (running demo):

      Set<String> tmpSet = new HashSet<String>(arrayList1);
      tmpSet.addAll(arrayList2);
      List<String> mergedList = new ArrayList<String>(tmpSet);
      

      * As correctly pointed out by Bruce Wayne, Double Brace initialization (the one-liner example, also used in both examples to populate the first two lists) should be used with care, due to the potential drawbacks described in the following article:

      Don’t be “Clever”: The Double Curly Braces Anti Pattern

    Explanation: Sets can't contain duplicates, so use one as transition vector.

    Example 1 code:

    List<String> arrayList1 = new ArrayList<String>(){{ add("One"); add("Two");   }};
    List<String> arrayList2 = new ArrayList<String>(){{ add("Two"); add("Three"); }};   
    List<String> mergedList = new ArrayList<String>(new HashSet<String>(arrayList1){{ addAll(arrayList2); }});
    System.out.println(mergedList);
    

    Output: [One, Two, Three]

    Example 2 code:

    List<String> arrayList1 = new ArrayList<String>(){{ add("One"); add("Two");   }}; 
    List<String> arrayList2 = new ArrayList<String>(){{ add("Two"); add("Three"); }}; 
    Set<String> tmpSet = new HashSet<String>(arrayList1);
    tmpSet.addAll(arrayList2);
    List<String> mergedList = new ArrayList<String>(tmpSet);
    System.out.println(mergedList);
    

    Output: [One, Two, Three]