Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
}
like image 978
VitoshKa Avatar asked Oct 19 '25 15:10

VitoshKa


1 Answers

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.

like image 59
JB Nizet Avatar answered Oct 21 '25 04:10

JB Nizet