2

I want to remove duplicated characters and spaces with java 8 streams api but my code is not working :

Stream.of(sentence.toCharArray()).flatMap(x->Character.valueOf(x)).
    distinct().sorted().forEach(System.out::print);

Please suggest a way use stream api for this.

2
  • 1
    This site is not a coding service. The way you contstruct your stream is not correct, try this baeldung.com/java-string-to-stream. Commented Apr 19, 2018 at 8:18
  • @Michal Thanks for the reference. Commented Apr 19, 2018 at 8:31

2 Answers 2

4

This should work

sentence.chars()
   .mapToObj(i -> (char)i)
   .distinct()
   .filter(x -> x != ' ')
   .sorted()
   .forEach(System.out::print);

Just a word of caution .chars() returns a IntStream and hence you need to cast it to char. You can check this post for further details on why String.chars() returns a IntStream

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @pvpkiran.
instead of filter(x -> x != ' ') is better to use filter(c -> ! Character.isWhitespace(c))
I’d move the .mapToObj(i -> (char)i) as far to the end as possible. Since here, all intermediate operations work (better) with int values, the best place would be right before the .forEach(System.out::print), the only operation where it matters. Or you use .forEach(i -> System.out.print((char)i)), then you don’t need to box to Character at all. You may get another performance benefit from using sentence.chars() .sorted().distinct() .filter(x -> x != ' ') .forEach(i -> System.out.print((char)i)), as .distinct() is capable of utilizing the sorted nature of the incoming data.
2

Stream#of does not support primitive char arrays. Therefore you're getting a Stream<char[]>. It would be better to use CharSequence#chars.

sentence.chars().mapToObj(c -> (char) c).distinct().sorted().forEach(Sytem.out::print);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.