1

In certain cases when I use a Stream on a list of Objects, I like to collect them via the Collectors.toMap function and assign an important attribute as the key and the object itself as the value, like in this case:

Map<String, SampleObject> map = list.stream()
    .collect(Collectors.toMap(SampleObject::getImportantValue, v -> v));

Usually I use the double colon operator to assign the key, but for the value I resort to the v -> v construct.

This made me wonder:

Is there a way to assign the object itself as the return value of the anonymous function by using double colons? From my own testing it appears that SampleObject and SampleObject:: don't work. (Only logical, as the former only references the class and the latter expects a method to follow)

As a naive approach I would expect something functionally similar to this:

...collect(Collectors.toMap(SampleObject::getImportantValue, SampleObject::));

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Jan5676
  • 13
  • 3
  • 3
    You can use `Function.identity()` instead of `v->v`. – JANO Mar 14 '22 at 14:47
  • 1
    Interesting, that works. I think you might as well post this as an answer, even though checking the implementation appears to just mask the arrow construct :p – Jan5676 Mar 14 '22 at 14:53

2 Answers2

2

Instead of using v->v you can use Function.identity(), which has the same effect. I personally like the second method more, but would not say that one is really better than the other. You can read in this answer about the differences if you are interested.

JANO
  • 2,995
  • 2
  • 14
  • 29
0

You should use the answer provided by JANO – either t -> t or Function.identity().

However, if you really really want to use a method reference, you could just roll out your own method:

class Functions {
    static <T> T identity(T t) {
        return t;
    }
}

and then suddenly

.collect(Collectors.toMap(SampleObject::getImportantValue, Functions::identity));

works.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130