Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining ArrayList without duplicates

Tags:

java

arraylist

import java.util.ArrayList;
import java.util.Collections;

public class SmartCombining {
    public static void main(String[] args) {
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        ArrayList<Integer> list2 = new ArrayList<Integer>();

        Collections.addAll(list1, 4, 3);
        Collections.addAll(list2, 5, 10, 4, 3, 7);

        smartCombine(list1, list2);
        System.out.println(list1);
        System.out.println(list2);
    }

    public static void smartCombine(ArrayList<Integer> first,
            ArrayList<Integer> second) {
        first.addAll(second);
    }    
}

So, I want to combine two lists into one, but if the second list contains a number from the first it won't be added. So far my method adds them all together.

like image 704
UkoM Avatar asked Oct 28 '14 18:10

UkoM


People also ask

Can you combine ArrayLists?

Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.

How do you combine elements in an ArrayList?

To join elements of given ArrayList<String> arrayList with a delimiter string delimiter , use String. join() method. Call String. join() method and pass the delimiter string delimiter followed by the ArrayList<String> arrayList .


1 Answers

Well, one way to do it is to iterate through the second list while checking if each element exists in the first list. If it doesn't, add it.

public static void smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
     for(Integer num : second) {      // iterate through the second list
         if(!first.contains(num)) {   // if first list doesn't contain current element
             first.add(num);          // add it to the first list
         }
     }
}  

Another way would be for you to hold your values inside a set (like HashSet) which doesn't allow any duplicates. Then you can combine them like:

first.addAll(second);

One more way you could do it is to first remove all elements from the first list that exist in the second list (the ones that would be duplicated). Then you add all elements of the second list to the first list.

public static void smartCombine(ArrayList<Integer> first, ArrayList<Integer> second) {
    first.removeAll(second); // remove elements that would be duplicated
    first.addAll(second);    // add elements from second list
}   
like image 169
nem035 Avatar answered Oct 01 '22 18:10

nem035