In Java the abstract version of a Reader that works with pulling Objects (instead of characters) is an Iterator.
The question is there an abstract version of Appendable or Writer where I can push objects (ie an interface)?
In the past I just make my own interface like:
public interface Pusher<T> {
public void push(T o);
}
Is there a generic interface that is available in most environments that someone knows about that makes sense so I don’t have to keep creating the above interface?
Update:
Here is an example of where it would be useful:
public void findBadCategories(final Appendable a) {
String q = sql.getSql("product-category-bad");
jdbcTemplate.query(q, new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
String id = rs.getString("product_category_id");
String name = rs.getString("category_name");
if (! categoryMap.containsKey(id)) {
try {
a.append(id + "\t" + name + "\n");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
});
}
I’m using an Appendable here but I would much rather have my Pusher callback. Believe me once Java 8 comes out I would just use closure but that closure still needs an interface.
Finally the other option I have chosen before is to completely violate Guava’s Predicate or Function (although that seems even worse). Its violation of the contract because these aim to be idempotent (although I suppose if you return true all the time… ).
What Guava does provide though is sort of analagous to Python’s generators thanks to its AbstractIterator.
I added an enhancement issue to Guava but I agree with them that its not really their job to add something fundamental like that.
Here is what I decided to do (and I think its the best option out of what others gave 😛 ).
I’m going to backport Java 8’s Lambda classes (
java.util.functions.*). Particularly this one:Basically I’ll make a new namespace like
com.snaphop.backport.java.util.functions.*and move over the interfaces and make them work with Guava. Obviously I won’t have the lambda syntax or the extension methods but those I can work around. Then in theory when Java 8 comes out it all I would have to do is a namespace switch.