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?
for (Iterator<String> it = mySet.iterator(); it.hasNext();) {
if(myList.contains(Integer.parseInt(it.next()))){
it.remove();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With