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.

prakash kumar
  • 520
  • 1
  • 5
  • 16

2 Answers2

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

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • Thanks @pvpkiran. – prakash kumar Apr 19 '18 at 08:35
  • 1
    instead of `filter(x -> x != ' ')` is better to use `filter(c -> ! Character.isWhitespace(c))` – Anton Balaniuc Apr 19 '18 at 10:41
  • 1
    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. – Holger Apr 19 '18 at 15:22
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);
Flown
  • 11,480
  • 3
  • 45
  • 62