Reputation: 5430
I am trying to convert Set to Map using java 8 using collectors.
Set<B2BUnitModel> payersList = .....
final Map<B2BUnitModel, List<B2BUnitPartnershipModel>> b2bUnitPartnershipMap = new HashMap<>();
final Map<B2BUnitModel, Object> map = payersList.stream().collect(Collectors.toMap(Function.identity(), Arrays::asList));
b2bUnitPartnershipMap.putAll(map); // Will throw Type Cast Error
I am not able to understand how do I convert Map values to B2BUnitPartnershipModel type since Arrays::asList
only will return Object
type.
Is there any way I can write something in Collectors.toMap(Function.identity(), Arrays::asList)
itself so that the api will return the desired Map (Map<B2BUnitModel, List<B2BUnitPartnershipModel>>
instead of Map<B2BUnitModel, Object>
).
I want to create a Map with Set value as a key and empty B2BUnitPartnershipModel
list.
Upvotes: 2
Views: 354
Reputation: 2210
Your Arrays::asList
causes problem. Try this:
Map<B2BUnitModel, List<B2BUnitPartnershipModel>> map = set.stream().collect(Collectors.toMap(Function.identity(), unit -> new ArrayList<>()));
Upvotes: 2
Reputation: 3791
Asuming B2BUnitModel
is Key
and B2BUnitPartnershipModel
is Value
the following code produces a map with keys from the set and empty lists as values using lambda expressions instead of method references.
@Test
public void testMapCollector() {
Set<Key> keySet = new HashSet<>();
keySet.add(new Key("key1"));
keySet.add(new Key("key2"));
keySet.add(new Key("key3"));
Map<Key, List<Value>> map = keySet.stream().collect(
Collectors.toMap(k -> k, key -> new ArrayList<>()));
System.out.println(map);
}
class Key {
String key;
public Key(String value) {
this.key = value;
}
@Override
public String toString() {
return "Key [key=" + key + "]";
}
}
class Value {
}
{Key [key=key1]=[], Key [key=key3]=[], Key [key=key2]=[]}
Upvotes: 4