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 request about why I need this function, this is a real use when I try to parse an integer into 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 think that IntStream.range(0, n).mapToObj(i -> base) could be simplified with something like Stream.of(base).times(n - 1) , unfortunately there is no times(int) for the stream object. Does anyone know how to do this?
java java-8 functional-programming
Gelin luo
source share