java.util.function.Function.identity方法的实际用途是什么?

aru*_*ngh 30 java java-8

为什么我应该使用Function.identity()返回它收到的相同内容而不使用输入做任何事情或以某种方式修改输入?

Apple apple = new Apple(10, "green");
Function<Apple, Apple> identity = Function.identity();
identity.apply(apple);
Run Code Online (Sandbox Code Playgroud)

必须有一些实际用法,我无法弄清楚.

Mar*_*eel 24

预期的用法是当您使用接受Function映射内容的方法时,需要将输入直接映射到函数的输出('identity'函数).

作为一个非常简单的示例,将人员列表从名称映射到人员:

import static java.util.function.Function.identity

// [...]

List<Person> persons = ...
Map<String, Person> = persons.stream()
        .collect(Collectors.toMap(Person::name, identity()))
Run Code Online (Sandbox Code Playgroud)

identity()功能只是为了方便和可读性.正如Peter在他的回答中指出的那样,你可以使用t -> t,但我个人认为使用identity()传达意图更好,因为它没有留下任何解释空间,就像想知道原作者是否忘记在那个lambda中进行转换一样.我承认,虽然这是非常主观的,并假设读者知道是什么identity().

可能它在内存方面可能有一些额外的优势,因为它重用单个lambda定义,而不是为此调用具有特定的lambda定义.我认为在大多数情况下,这种影响可能微不足道.


Pet*_*rey 13

例如,您可以将其用于频率计数.

public static <T> Map<T, Long> frequencyCount(Collection<T> words) {
    return words.stream()
            .collect(Collectors.groupingBy(Function.identity(),
                    Collectors.counting());
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您说组分组的键是集合中的元素(不转换它).

就个人而言,我发现这个更简洁

import static java.util.stream.Collectors.*;

public static Map<String, Long> frequencyCount(Collection<String> words) {
    return words.stream()
            .collect(groupingBy(t -> t,
                    counting());
}
Run Code Online (Sandbox Code Playgroud)

  • @MarkRotteveel对.我的意思是[这](/sf/answers/1962903631/) (3认同)