Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 function that always return the same value without regarding to 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 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?

like image 699
Gelin Luo Avatar asked May 14 '14 21:05

Gelin Luo


People also ask

Which functional interface would you use for the following no parameters returns a value?

IntConsumer functional interface represents an operation that accepts a single int-valued argument and returns no result.

What is TriFunction in Java?

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) .

What is lambda expression in Java 8 with example?

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.

What is Functionalinterface?

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.


1 Answers

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
like image 140
Joachim Isaksson Avatar answered Oct 23 '22 23:10

Joachim Isaksson