VitoshKa
VitoshKa

Reputation: 8523

Collect into a HashSet using Java8 stream over a set gives `Type Mismatch` Error

The following code compiles as expected:

import java.util.Arrays;
import java.util.HashSet;
import java.util.stream.Collectors;

public class Test2 {
    String[] tt = new String[]{ "a", "b", "c"};

    HashSet<String> bb =
        Arrays.asList(tt).stream().
        map(s -> s).
        collect(Collectors.toCollection(HashSet::new));
}

If I change tt to be a HashSet the Eclipse compiler fails with the message Type mismatch: cannot convert from Collection<HashSet<String>> to HashSet<String>:

public class Test2 {
    HashSet<String> tt = new HashSet<String>(Arrays.asList(new String[]{ "a", "b", "c"}));

    HashSet<String> bb =
        Arrays.asList(tt).stream().
        map(s -> s).
        collect(Collectors.toCollection(HashSet::new));
}

Upvotes: 4

Views: 9486

Answers (1)

JB Nizet
JB Nizet

Reputation: 691765

That's expected. Arrays.asList() takes a vararg as argument. It thus expects several objects, or an array of objects, and stores those objects in a list.

You're passing a single HashSet as argument. So this HashSet is stored in a list, and you thus end up with a list containing a single HashSet.

To transform a Set into a List, use new ArrayList<>(set). Or, just don't transform it to a list, as it's unnecessary.

Upvotes: 4

Related Questions