Java 8函数始终返回相同的值而无需考虑参数 [英] Java 8 function that always return the same value without regarding to parameter
问题描述
Java 8中是否有一个预定义的函数,其功能如下:
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));
}
}
我猜想IntStream.range(0, n).mapToObj(i -> base)
可以简化为Stream.of(base).times(n - 1)
之类的东西,不幸的是流对象上没有times(int)
方法.有人知道怎么做吗?
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?
推荐答案
一个简单的lambda,x -> val
似乎等同于您的方法;
A simple lambda, x -> val
seems to be equivalent to your method;
Function<Integer, Integer> test1 = constant(5);
Function<Integer, Integer> test2 = x -> 5;
...两者都忽略输入,并在应用时输出常量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
这篇关于Java 8函数始终返回相同的值而无需考虑参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!