Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Set & List in my case

I have a List<Integer> , this list contains duplicated elements:

//myList content is something like e.g. 1,2,1,3,3,6,7,...
List<Integer> myList = getNumbers();

I have also an Set<String> , as you all know, Set only contain unique elements, no duplicated one. My Set<String> contains String-type-integers:

//The Set content is String type integer , e.g. "1", "3", "5" …
Set<String> mySet = getNumSet(); 

I would like to compare mySet with myList to figure out what elements mySet has but myList doesn't have & remove those elements from mySet.

The way I do now is to use nested iteration like following:

for(Integer i : myList){
   for(String s : mySet){
         if(!myList.contains(Integer.valueOf(s))){
               mySet.remove(s);
         }
    }   

}

Is there more efficient way than mine to do it?

like image 632
Leem.fin Avatar asked Oct 18 '25 14:10

Leem.fin


2 Answers

    for (Iterator<String> it = mySet.iterator(); it.hasNext();) {
        if(myList.contains(Integer.parseInt(it.next()))){
            it.remove();
        }
    }
like image 67
pasha701 Avatar answered Oct 21 '25 03:10

pasha701


The easiest way may be using Collection#retainAll(Collection<?> c) which could be implements with some optimization in function of the collection's type.

mySet.retainAll(myList)

However mySet and myList must be Set<X> and List<X>. I advice you to change the declaration of mySet and fill it with something like Integer#valueOf(String s), then use the retainAll method.

like image 36
NiziL Avatar answered Oct 21 '25 05:10

NiziL