Question

How can I remove duplicates in an ArrayList in Java, except for specific elements? For instance if I have an ArrayList with

"a", "b", "c", "d", "d", "a", "b", "b", "d", "c"

I only want to remove the duplicates for "a", "b" and "c" and I also need to maintain the order of the elements. The duplicates of "d" cannot be removed.

How can I accomplish this?

Was it helpful?

Solution

You will have to maintain 2 lists:

One which is the actual list while the other is removeDuplicated list which tells your program which entries to keep unique.

Also, you can maintiain the order by either using a LinkedList or a ArrayList.

OTHER TIPS

I would create 2 arrayList. One with the values and one with the values you want to remove. Simply do a removal with the list of the values you no longer want.

public class SOTest
{
    public static void main(String[] args)
    {
     String [] strAr = {"a", "b", "c", "d", "d", "a", "b", "b", "d", "c"};
     String [] removeAr = {"a", "b"};

     ArrayList<String> arList = new ArrayList<String>(Arrays.asList(strAr));
     ArrayList<String> removeList = new ArrayList<String>(Arrays.asList(removeAr));
     arList.removeAll(removeList);

     for(String s : arList)
         System.out.println(s);
    }
}

I would create another array without duplicates.

Create another array(list2) and add elements from source array(list1) if list2 does not contain the same element except for "d".

ArrayList<String> list1;
ArrayList<String> list2;

for(int i=0;i<list1.size();i++) {
    String element = list1.get(i);
    if((!element.equals("d")) && (!list2.contains(element))) {
        list2.add(element);
    }
}

I do not want to write code if this is a homework exercise for you.

Do the following.

  1. Define a HashSet of not allowed items ('a','b','c') and an empty HashSet called elimination set.

  2. Iterate through the ArrayList.

  3. Test the item against elimination HashSet and remove the item from ArrayList if the item is in elimination set.

  4. Test the item against not allowed HashSet and add the item to elimination HashSet if the item is in not allowed set.

Time complexity is O(n) where n is length of ArrayList.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top