I’m using jdk 17.
I want to use a concise syntax like
var totalSet = IntStream.range('1', '9').map(i -> (char) i).boxed().collect(Collectors.toSet()); // type of totalSet is `Set<Integer>`
to create a Set<Character> contains value from ‘0’ to ‘9’, (the type of totalSet is Set<Integer> with above)
Other concise syntaxes to do this are appreciated.
>Solution :
You need to use operation mapToObj() (not map()) to transform IntStream into a Stream<Character>.
When you apply .map(i -> (char) i) in the IntStream (a stream of primitive int values) it only performs primitive conversion from int to char (reminder: char is a numeric type), and then the result would be promoted back into int.
And when you apply boxed() on the IntStream you’re getting Stream<Integer> (a stream of integer wrappers).
Set<Character> totalSet = IntStream.range('1', '9')
.mapToObj(i -> (char) i)
.collect(Collectors.toSet());