"I've come to realize that Functional Interface and other things are useful, but what do you use this" identity "for? What on earth do you want to return a function that just returns?" I was told, so it's a very new memo.
//If there is such a class
@Data
class Obj {
private int id;
private String data;
}
//Suppose it is a List
List<Obj> list = <some>;
// key:id, value:Generate map of obj(* I feel like I have a better hand)
Map<Integer, Obj> map = list.stream().collect(Collectors.toMap(obj::getId, Function.identity()));
Functional Interface is an interface for receiving "the operation itself". It treats all kinds of operations like that with signatures. However, when I write things using this bang bang, it is not uncommon for me to say, "No, you can just leave it as it is! Don't do anything!" Identity is useful in such cases.
Of course you can do the same thing with lambda, like o-> o, but it's not exactly the same. It's notorious that the entity of lambda is an anonymous local class, which means that the more you use it, the more classes and instances you use. That means a little load. (That's right, being able to pass it as an argument means that it has an entity as an object)
On the other hand (depending on the JVM implementation) identity always returns the same instance: https://stackoverflow.com/questions/28032827/java-8-lambdas-function-identity-or-t-t Certainly, if it surely ends in one shot, it's okay to write it with lambda. However, basically, using Function.identity or UnaryOperator.identity has the advantage that you can rest assured that you will not inadvertently mass-produce useless instances. Let's forgive a little more types and imports.
identity = identity. The method identity returns an identity function. An identity function is a "function that returns the passed arguments" and is the identity element in the combination of functions. In other words, it's like the number 1 (although it depends on the area of the context, but sensuously).
Recommended Posts