Java - not anonymous Comparator analogue to select elements from collection -
i have interest problem. there's abstract class, extended subclasses. in abstract class there's following method:
public abstract class myabstractclass { protected list<myobject> findspecificobjects(list<myobject> objectstoselectfrom, list<myobject> objectstocompare) { list<myobject> selected = new arraylist<myobject>(); //there need select elements objectstoselectfrom //using mycomparatoranalogue objectstocompare return selected; } protected class mycomparatoranalogue implements ??? { /*this comparator analogue should have access objectstocompare must select elements objectstoselectfrom property myproperty=somevalue, somevalue - value no 1 element objectstocompare have in same property myproperty */ } }
why should such strange way - because need able override mycomparator in subclasses. there way want to? looked @ apache commons collections, didn't find me in situation.
for example:
objectstoselectfrom = {[key=michael,value=23],[key=luis,value=44],[key=andrew,value=26]} objectstocompare = {[key=john,value=23],[key=luis,value=44]}
assuming myproperty
value
property mycomparatoranalogue
should select [key=andrew,value=26]
element.
hope described accessibily. thanks.
using java 8 , streams, this.
list<myobject> l = new arraylist<>(); l.add(new myobject("foo", "foo")); l.add(new myobject("bar", "bar")); l.add(new myobject("baz", "baz")); list<myobject> whitelist = new arraylist<>(); whitelist.add(new myobject("other bar", "bar")); predicate<? super myobject> inwhitelist = (myobject o) -> { return whitelist.stream().anymatch((p) -> o.getvalue().equals(p.getvalue())); }; list<myobject> filtered = l.stream().filter(inwhitelist).collect(collectors.tolist());
now filtered
contains myobject("bar", "bar")
has same value
myobject("other bar", "bar")
.
Comments
Post a Comment