Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 681
SnG Avatar asked Mar 26 '26 10:03

SnG


1 Answers

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());
like image 166
Sweeper Avatar answered Mar 28 '26 23:03

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!