java - Is there any way to use BiConsumers as simply as Consumers? -
this theorical question no concrete application.
i have following method not touch. (if possible @ all) used biconsumer.
void dosmallthing(a a, b b) { // , b. } void dobigthing(list<a> as, b b) { // do? } how can iterate on as while keeping b constant , use this::dosmallthing in dobigthing?
of course following doesn't work.
void dobigthing(list<a> as, b b) { as.stream() .foreach(this::dosmallthing); } the following works nice , use everyday.
void dobigthing(list<a> as, b b) { as.stream() .foreach(a -> dosmallthing(a, b)); } the following works well, bit more tricky.
consumer<a> dosmallthingwithfixedb(b b) { return (a) -> dosmallthing(a, b); } void dobigthing(list<a> as, b b) { as.stream() .foreach(dosmallthingwithfixedb(b)) } but of solutions don't simplicity of consumer case. there simple exists biconsumer?
you want "bind" function argument. unfortunately there's no built-in mechanism in java 8 (except binding object instance methods this::). may generalize dosmallthingwithfixedb method this:
public class bind { public static <a, b> consumer<a> bindlast(biconsumer<a, b> fn, b b) { return -> fn.accept(a, b); } public static <a, b> consumer<b> bindfirst(biconsumer<a, b> fn, a) { return b -> fn.accept(a, b); } } and use:
void dobigthing(list<a> as, b b) { as.stream() .foreach(bind.bindlast(this::dosmallthing, b)); } probably there's third-party library contains such methods. using explicit lambda seems ok me. should not try express method references.
Comments
Post a Comment