A Java 8 function that always returns the same value without specifying a parameter

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?

+7
java java-8 functional-programming
source share
1 answer

Simple lambda, x -> val seems equivalent to your method;

 Function<Integer, Integer> test1 = constant(5); Function<Integer, Integer> test2 = x -> 5; 

... both ignore the input and output a constant of 5 when applied;

 > System.out.println(test1.apply(2)); 5 > System.out.println(test2.apply(2)); 5 
+10
source share

All Articles