-5

I have two lists of my custom class

public class WiSeConSyncItem{
   int processId=1;//unique
   int syncStatus=0;//variable
}

And List<WiSeConSyncItem> mainItems=new ArrayList();

mainItems will iterate and execute corresponding API's( take time). And another timer will add some data to mainItems.

So if we added the second list to mainItems, it may contain duplicated items. So I want to remove the duplicated item from the second list and add to the first list.

The remove duplicate function

public static List<WiSeConSyncItem> removeDuplicate(List<WiSeConSyncItem> syncItems) {
    Set set = new TreeSet(new Comparator<WiSeConSyncItem>() {
        @Override
        public int compare(WiSeConSyncItem o, WiSeConSyncItem o1) {
            if (o.getProcessId() == o1.getProcessId())
                return 0;//to remove duplicate
            else
                return 1;
        }
    });

    set.addAll(syncItems);
    return new ArrayList<>(set);
}

I can't remove the items from mainItems because that objects may be executing by other threads. I can't use Set or HashMap because of this item came from another sdk. ( yeh I can create a new model from it, but please suggest from this content)

noobEinstien
  • 3,147
  • 4
  • 24
  • 42
  • Don't use a [`List`](https://docs.oracle.com/javase/7/docs/api/java/util/List.html), use a [`Set`](https://docs.oracle.com/javase/7/docs/api/java/util/Set.html) that will prevent duplicates... that will solve your problem from the start. For the actual demands, please try and post what you have. It is not hard to find some existing request on "_removing duplicated in `List`_" to at least start to solve the problem. – AxelH Mar 27 '18 at 06:24

1 Answers1

0

if they need to be unique and concurrently accessed, why not put it them into a ConcurrentHashMap ? in that way, you avoid duplicates and also, you can add items concurrently:

Map<Integer,WiSeConSyncItem> db = new ConcurrentHashMap<Integer,WiSeConSyncItem>();
WiSeConSyncItem item = new WiSeConSyncItem();
item.processId=1;
db.put(item.processId, item);
dsncode
  • 2,407
  • 2
  • 22
  • 36