问题
I'm looking for the inverse of Supplier<T> in Guava. I hoped it would be called Consumer – nope – or Sink – exists, but is for primitive values.
Is it hidden somewhere and I'm missing it?
I'd like to see it for the same kinds of reasons that Supplier is useful. Admittedly, uses are less common, but many of the static methods of Suppliers, for example, would apply in an analogous way, and it would be useful to express in one line things like "send this supplier every value in this iterable".
In the meantime, Predicate and Function<T,Void> are ugly workarounds.
回答1:
Your alternatives are:
- Java 8 introduces a Consumer interface which you can compose.
- Xtend's standard library contains Procedures.
- Scala has Function*; if a function's return type is Unit, it is considered a side effect.
In all of these languages, you can use functional interfaces conveniently, so you could also use e.g. Functional Java's Effect.
Otherwise, you better rely on existing language constructs for performing side effects, e.g. the built-in for loop. Java < 8 inflicts tremendous syntactic overhead when using lambdas. See this question and this discussion.
回答2:
You can use a Function and set the second Argument to java.lang.Void this Function can only return null.
回答3:
You have already found the answer. If you just want to visit, you can use filter with a predicate that always returns true; if you are super defensive you can use any predicate and use an or function with an alwaysTrue in the filter itself; just add the or at the end to avoid shortcircuiting.
The problem is that even though I agree that conceptually Predicate and Consumer are different since a Predicate should be as stateless as possible and not have side effects while a consumer is only about the side effects, in practice the only syntactic difference is that one returns a boolean (that can be ignored) and the other void. If Guava had a Consumer, it would need to either duplicate several of the methods that take a Predicate to also take a Consumer or have Consumer inherit from Predicate.
来源:https://stackoverflow.com/questions/14702380/inverse-of-suppliert-in-guava