Many lambdas for the Function
interface take the form
t -> {
// do something to t
return t;
}
I do this so often that I have written a method for it like this.
static <T> Function<T, T> consumeThenReturn(Consumer<T> consumer) {
return t -> {
consumer.accept(t);
return t;
};
}
This enables me to do really nice things like this:
IntStream.rangeClosed('A', 'Z')
.mapToObj(a -> (char) a)
.collect(Collectors.collectingAndThen(Collectors.toList(), consumeThenReturn(Collections::shuffle)))
.forEach(System.out::print);
Is there another way to do conversions like this without relying on my own method? Is there anything in the new APIs I have missed that makes my method redundant?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…