Free-Minded
Free-Minded

Reputation: 5430

Issue while converting Set to Map

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

Answers (2)

MBec
MBec

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

cjungel
cjungel

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.

Code

@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 {
}

Output

{Key [key=key1]=[], Key [key=key3]=[], Key [key=key2]=[]}

Upvotes: 4

Related Questions