I'm trying to write my own "functional" little lib in Java. If I have this function :
public static <T> List<T> filter(Iterable<T> source,BooleanTest predicate)
{
List<T> results = new ArrayList<T>();
for(T t : source)
{
if(predicate.ok(t))
results.add(t);
}
return results;
}
why can't I use it with this snippet:
String strings[] = {"one","two","three"};
List<String> containingO = IterableFuncs.filter(strings,new BooleanTest() {
public boolean ok(String obj) {
return obj.indexOf("o") != -1;
}
});
As far as I know, a Java array implements Iterable, right? What needs to be changed to make the function work with arrays, as well as collections? By choosing Iterable as the first parameter, I figured I got all cases covered.
Arrays don't implement any interfaces in Java, unfortunately. The enhanced for loop works over arrays and iterables, separately.
However, you can use Arrays.asList(T...) to wrap an array in a List<T> which is iterable.
In terms of the "functional library" side of things, you should probably have a look at Google Collections which has a lot of similar stuff in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With