EnzoG
EnzoG

Reputation: 13

Java: Convert List<someType> to Map<someType, new HashSet<OtherType>>

I am currently trying to find a way of converting a List of some Type to a Map whose keys are the List elements and the values are an empty new HashSet of a different Type...

Is there some way of achieving this using streams and without using a loop?

Loop would be something like:

List<SomeType> xList = ...
HashMap<SomeType, HashSet<OtherType>> map = new HashMap<SomeType, HashSet<OtherType>>();
for (SomeType x: xList) {
  map.put(x, new HashSet<OtherType>());
}

What I tried so far is something like Map<SomeType, HashSet<OtherType>> test = xList.stream().collect(Collectors.toMap(x -> x, new HashSet<OtherType>())); but this wont even compile and I am quite clueless about streams....

Upvotes: 1

Views: 179

Answers (2)

Suic
Suic

Reputation: 443

You could do something like this

List<Integer> numbers = IntStream.rangeClosed(0, 10).boxed().collect(Collectors.toList());
Map<Integer, Set<String>> map = numbers.stream()
                    .collect(Collectors.toMap(x -> x, HashSet::new));

Upvotes: 1

dreamcrash
dreamcrash

Reputation: 51433

You were close with:

Map<SomeType, HashSet<OtherType>> test = xList.stream().collect(Collectors.toMap(x -> x, new HashSet<OtherType>()));

But it is actually :

List<SomeType> xList = new ArrayList<>();
HashMap<SomeType, HashSet< OtherType >> map = xList.stream()
        .collect(Collectors.toMap(i -> i, v -> new HashSet<OtherType>());

The Collectors.toMap expects a Function in both parameters. Instead of i -> i you can use Functions.identity() and instead of v -> new HashSet<OtherType>() you can use HashSet::new as follows:

xList.stream()
     .collect(Collectors.toMap(Functions.identity(), HashSet::new);

Upvotes: 3

Related Questions