I played with my idea how to do it. I cannot think of a way to do this without any iteration.
Suppose you have a method with a name distance(String,String):intthat returns a given distance between two lines.
String x = "Obi-wan";
List<String> items = new ArrayList<String>(asList("Luke","Yoda","Anakin"));
if (items.filter(s -> distance(s, x) >= 3).getFirst() == null) {
items.add(x);
}
If you use JDK8 Preview , you can do this as soon as possible using the code above. The Iterables.getFirst () method will not iterate the entire collection, but only until the first item that matches the criteria is found.
, , Predicate .
interface Predicate<T> {
public boolean eval(T o);
}
public static void main(String[] args) {
final String x = "Obi-wan";
List<String> items = new ArrayList<String>(asList("Luke","Yoda","Anakin"));
Predicate<String> p = new Predicate<String>() {
public boolean eval(String s){
return distance(s, x) >= 3;
}
};
if(filter(items, p).isEmpty()){
items.add(x);
}
}
public static <T> List<T> filter(List<? extends T> items, Predicate<? super T> predicate){
List<T> destiny = new ArrayList<T>();
for(T item : items){
if(predicate.eval(item){
destiny.add(item);
}
}
return destiny;
}
, , .