java - removeAll method with different object types -
i have 2 lists on want mass operations using method removeall, retainall, contains. problem both lists have different type of objects having 1 field same. like
class objecttype1{ long field1; string field2; string field3 } class objecttype2{ long field1; string field4; long field5
}
so list1 contains elements of objecttype1, , list2 contains objecttype2. want mass operations based on field1 mutual in both object types.
i thinking of implementing equals method in both objects based on mutual field. thought may wrong create equals on 1 field in future there may need add together comparing based on other fields in equals method. please suggest.
hope have made query clear enough. please allow me know clarifications.
have @ google's guava library. can utilize collections2.transform
accomplish this. here's how retainall()
, example:
import com.google.common.base.function; import com.google.common.collect.collections2; ... list<objecttype1> list1 = ...; list<objecttype2> list2 = ...; colection<long> list1field1 = collections2.transform(list1, new function<objecttype1, long>() { public long apply(objecttype1 input) { homecoming (null == input) ? null : input.field1; } }); collection<long> list2field1 = collections2.transform(list2, ...); // list1.retainall(list2) based on field1 equivalence list1field1.retainall(list2field1); // affects underlying list, ie list1.
java collections
No comments:
Post a Comment