2

While reading effective java Chapter 5, Item 27

It talks about generic singleton pattern :

Now suppose that you want to provide an identity function. It would be wasteful to create a new one each time it’s required, as it’s stateless. If generics were reified, you would need one identity function per type, but since they’re erased you need only a generic singleton. Here’s how it looks:

public class GenericSingleton<T> {
    private static UnaryFunction<Object> IDENTIFY_FUNCTION = new UnaryFunction<Object>() {
        @Override
        public Object apply(Object args) {
            return args;
        }
    };

    @SuppressWarnings("unchecked")
    public static <T> UnaryFunction<T> identityFunction() {
        return (UnaryFunction<T>) IDENTITY_FUNCTION;
    }

    public static void main(String[] args) {
        String[] strings = {"jute", "hemp", "nylon"};
        UnaryFunction<String> sameString = identityFunction();
        for (String s : strings) {
            System.out.println(sameString.apply(s));
        }
        Number[] numbers = {1, 2.0, 3L};
        UnaryFunction<Number> sameNumber = identityFunction();
        for (Number n : numbers) {
            System.out.println(sameNumber.apply(n));
        }
    }
}

I can't understand what does apply method actually do!
It's like getting an object and returning itself. why? some useless sample?

Would someone tell me the use case please ?

alizeyn
  • 2,300
  • 1
  • 20
  • 30

1 Answers1

4

A use case is the Collectors.toMap().

Say you have a list of items identified by a unique key and you want a Map from that unique key to the object itself.

Collectors.toMap() needs two functions:

  • one to extract the key from the object
  • another one to extract the value from the object

Since the value should be the object itself, you need a function that takes an object and returns the same object - which is your identity function.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34