20230418 java Function.identity

Java 8 identity function Function.identity() returns a Function that always returns it’s input argument.

和f(x)=x一个意思

public class Java8FunctionIdentityExample1 {

  public static void main(String[] args) {
    
    Function<Integer, Integer> identityFunction = Function.identity();
    Function<Integer, Integer> intFunction = e -> e; // using lambda expression
    
    System.out.println(identityFunction.apply(10)); // 10 
    System.out.println(intFunction.apply(10)); // 10
    
    List<String> names = Arrays.asList(
         "Peter",
         "Martin",
         "John",
         "Vijay",
         "Arthur"
        );
    
    // Just for example
    System.out.println("----- Function.identity() -----");
    names.stream().map(Function.identity()).forEach(System.out::println);
    
    System.out.println("----- Function(e-> e) -----");
    names.stream().map(e->e).forEach(System.out::println);
  }
}

Output

10
10
----- Function.identity() -----
Peter
Martin
John
Vijay
Arthur
----- Function(e-> e) -----
Peter
Martin
John
Vijay
Arthur

源码

@FunctionalInterface
public interface Function<T, R> {
	//....

	// 静态方法 (Java 8允许在接口中加入具体方法。接口中的具体方法有两种,default方法和static方法)
	// 返回一个Function对象,即lambda表达式对象
	static  Function identity() {
	    return t -> t;
	}
}

什么时候会用到这个方法??我疑惑

当我们使用Stream时,要将它转换成其他容器或Map。这时候,就会使用到Function.identity()。

Stream<String> stream = Stream.of("This", "is", "a", "test");
Map<String, Integer> map = stream.collect(Collectors.toMap(Function.identity(), String::length));

注意有时候不能用它代替i -> i

有时候不能使用Function.identity,看下面的例子:

List list = new ArrayList<>();
list.add(1);
list.add(2);

下面这段代码可以运行成功:

int[] arrayOK = list.stream().mapToInt(i -> i).toArray();

但是如果你像下面这样写:

int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();

运行的时候就会错误,因为mapToInt要求的参数是ToIntFunction类型,但是ToIntFunction类型和Function没有关系。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值