Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a `HashSet<Character>` contains '0'-'9' using stream api?

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading