使用场景
当我们使用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));
如上代码,转化后的map中的key为stream中的字符串,value为字符串的长度。使用Function.identity()返回一个输出跟输入一样的Lambda表达式对象,等价于t -> t。下面的代码可以达到同样的效果。
Stream<String> stream2 = Stream.of("This", "is", "a", "test");
Map<String, Integer> map2 = stream2.collect(Collectors.toMap(str -> str, String::length));
Function.identity()可以代替所有的t -> t表达式吗?
答案是NO
只有方法的传参是Function接口类别的时候,才能使用Function.identity()。
比如下面代码,使用i -> i是OK的,但是使用Function.identity()就会报错,因为mapToInt方法的传参不是Function类型。
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
int[] arrayOK = list.stream().mapToInt(i -> i).toArray();
Stream接口的mapToInt方法源码如下
IntStream mapToInt(ToIntFunction<? super T> mapper);