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::));

2
  • 3
    You can use Function.identity() instead of v->v. Commented Mar 14, 2022 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 Commented Mar 14, 2022 at 14:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.