我有兴趣问题。这是一个抽象类,将由子类扩展。 在抽象类中,有以下方法:
public abstract class MyAbstractClass {
protected List<MyObject> findSpecificObjects(List<MyObject> objectsToSelectFrom, List<MyObject> objectsToCompare) {
List<MyObject> selected = new ArrayList<MyObject>();
//there I need to select elements from objectsToSelectFrom
//using MyComparatorAnalogue with objectsToCompare
return selected;
}
protected class MyComparatorAnalogue implements ??? {
/*this comparator analogue should have an access to objectsToCompare
it must select elements from objectsToSelectFrom with property myProperty=someValue, where someValue - value that no one element from objectsToCompare have in the same property myProperty
*/
}
}
我为什么要这么奇怪地做 - 因为我需要能够在子类中覆盖MyComparator。有什么方法可以做我想做的事吗?我查看了Apache Commons Collections,但在这种情况下找不到任何可以帮助我的东西。
例如:
objectsToSelectFrom = {[key=Michael,value=23],[key=Luis,value=44],[key=Andrew,value=26]}
objectsToCompare = {[key=John,value=23],[key=Luis,value=44]}
假设myProperty
value
属性MyComparatorAnalogue
应选择[key=Andrew,value=26]
元素。
希望我把它描述为accessibily。感谢。
答案 0 :(得分:1)
使用Java 8和流,你可以做这样的事情。
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());
现在filtered
包含的MyObject("bar", "BAR")
与value
具有相同的MyObject("other bar", "BAR")
。