问题
Is there a predefined Function in Java 8 that does something like this:
static <T, R> Function<T, R> constant(R val) {
return (T t) -> {
return val;
};
}
To answer people's query on why I need this function here is the real usage when I am trying to parse an integer to an roman numerals:
// returns the stream of roman numeral symbol based
// on the digit (n) and the exponent (of 10)
private static Stream<Symbol> parseDigit(int n, int exp) {
if (n < 1) return Stream.empty();
Symbol base = Symbol.base(exp);
if (n < 4) {
return IntStream.range(0, n).mapToObj(i -> base);
} else if (n == 4) {
return Stream.of(base, Symbol.fifth(exp));
} else if (n < 9) {
return Stream.concat(Stream.of(Symbol.fifth(exp)),
IntStream.range(5, n).mapToObj(i -> base));
} else { // n == 9 as n always < 10
return Stream.of(base, Symbol.base(exp + 1));
}
}
And I guess the IntStream.range(0, n).mapToObj(i -> base)
could be simplified to something like Stream.of(base).times(n - 1)
, unfortunately there is no times(int)
method on stream object. Does anyone know how to make it?
回答1:
A simple lambda, x -> val
seems to be equivalent to your method;
Function<Integer, Integer> test1 = constant(5);
Function<Integer, Integer> test2 = x -> 5;
...both ignore the input and output the constant 5 when applied;
> System.out.println(test1.apply(2));
5
> System.out.println(test2.apply(2));
5
来源:https://stackoverflow.com/questions/23665502/java-8-function-that-always-return-the-same-value-without-regarding-to-parameter