Java 8 function that always return the same value without regarding to parameter

前端 未结 1 1792
梦如初夏
梦如初夏 2021-01-17 23:43

Is there a predefined Function in Java 8 that does something like this:

static  Function constant(R val) {
    return (T t) -> {
          


        
相关标签:
1条回答
  • 2021-01-17 23:57

    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
    
    0 讨论(0)
提交回复
热议问题