Convert List<T> to Map<T, U> using Java 8

SnG :

I'm trying to convert a List<T> to Map<T, U> using Java 8 but I keep getting stuck at this one part. What I am trying to have is the value of the map to be of some variable of type U. Lets say for this example that T is a Person object and U is a String.

list.stream().collect(Collectors.toMap(x -> x, ""));

However, I keep getting the following error under x -> x:

no instance of type variable T,U exists so that String conforms to Function<? super T, ? extends U>

Any ideas on what the issue can be?

Sweeper :

A map is a collection of key value pairs. You mentioned that you want the keys to be instances of Person, but what about the values? What do you want the values to be?

If you want the values to be the person's name, then you can do:

list.stream().collect(Collectors.toMap(x -> x, Person::getName));

If you somehow just want all the values to be "" (I don't think this is very useful though), you still need a lambda:

list.stream().collect(Collectors.toMap(x -> x, x -> ""));

It seems like you might just want a bunch of unique values, in which case you could use Collectors.toSet:

list.stream().collect(Collectors.toSet());

Or just distinct:

list.stream().distinct().collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87276&siteId=1