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?
IntConsumer functional interface represents an operation that accepts a single int-valued argument and returns no result.
Interface TriFunction<T,U,V,R> Represents a function that accepts three arguments and produces a result. This is the three-arity specialization of Function . This is a functional interface whose functional method is apply(Object, Object, Object) .
Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With