I have 2 array-list called assignment and person and both of different type and different sizes also. Problem statement :I wanna remove items from person where person id equals assignment id, i hv written following Comparator.
SortedSet<Map.Entry<AssignmentResults, Person>> text = new TreeSet<Map.Entry<AssignmentResults, Person>>(
new Comparator<Map.Entry<AssignmentResults, Person>>() {
@Override
public int compare(Entry<AssignmentResults, Person> lhs,
Entry<AssignmentResults, Person> rhs) {
// TODO Auto-generated method stub
int statusvalue = 0;
if (rhs.getValue().getId()
.equals(lhs.getKey().getId()))
statusvalue = 1;
return statusvalue;
}
});
But im not sure how to use this to get person arraylist where all item which does not contains assignment id will be removed.plz any help will be appreciated. I need logic which is robust with less complexity
You can save all assigments' ids to HashSet
and then remove items from list of persons with for-loop
:
Set<Long> assigmentsIdsSet = new HashSet<Long>(); // here we will store all assigments' ids
for (AssignmentResults assigment : assigmentsList) { // assigmentsList is your array list of assigments
assigmentsIdsSet.add(assigment.getId());
}
// now go through list of persons and remove persons with ids from assigmentsIdsSet
for (Iterator<Person> it = personList.iterator(); it.hasNext(); ) {
if (assigmentsIdsSet.contains(it.next().getId())) {
it.remove();
}
}
ArrayOutOfBounds
exception It's confusing: you intend to work on lists and you compare map entries.
You could just:
Have your Person
and Assignment
classes both implement a common interface with getId
.
Overide equals
in both classes so that objects with the same id are equal. You would cast Object
parameters to instances of your common interface with getId
.
You should also overide hashCode
so that objects with the same id have the same hashcode. You could just return getId().getHashCode()
if id is an object.
You can then do persons.removeAll(assignments)
As a side note, all of this is not really "clean"; but it would get the job done for that specific use case. Just don't rely on this if you intend to provide a library with many other use cases
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.