I have a set and I want to convert it to map in order to use it later in guava's Maps.difference()
. I only care about the keys in the difference.
Came up with this version:
private <T> Map<T, T> toMap(Set<T> set) {
return set.stream().collect(Collectors.toMap(Function.identity(), Function.identity()));
}
However, I know that usually, a set has a backing field of map. This is the method I use to create the map:
public static <E> Set<E> newConcurrentHashSet() {
return Collections.newSetFromMap(new ConcurrentHashMap<E, Boolean>());
}
Since I only need the keys I thought maybe I can get a view of this field somehow. any idea?
I ended up with a fairly straight-forward one line solution with Java 8 as follows:
Map<String, Foo> map = fooSet.stream().collect(Collectors.toMap(Foo::getKey, e -> e));
Set<Foo> fooSet
getKey
which returns a StringImprovement of developer's answer:
Map<String, Foo> map = fooSet.stream().collect(Collectors.toMap(Foo::getKey, Function.identity()));
or if you statically import Collectors.toMap
and Function.identity
:
Map<String, Foo> map = fooSet.stream().collect(toMap(Foo::getKey, identity()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With