Home > Enterprise >  How do I sort each string within a stream of strings?
How do I sort each string within a stream of strings?

Time:12-10

I am attempting to apply the map() function to a stream of strings right now such that the new stream contains a sorted version of each string. That is, instead of "cat" it will have "act". I am attempting to run the method as so:

Stream<String> sortedStream = validWordStream.map(s -> Arrays.sort(s.toString().toCharArray()));

However, it complains that the stream returned is a stream of Objects, not Strings: enter image description here

Question

What intuitive changes do I have to make to the map() function such that I get a stream of sorted strings?

CodePudding user response:

since Array.sort's return type is void, you can not use its value as map result. Also, you won't have correct result if there are surrogate pairs.

So:

Stream<String> validWord = foo();
Stream<String> validSortedWord = validWord
    .map(s -> s.codePoints().sorted().toArray())
    .map(sortedCodepoints -> new String(sortedCodePoints, 0, sortedCodePoints.length))

(Edit: changed 3rd arguments of String constructor, see Sree Kumar's comment)

CodePudding user response:

Sort each char array and then generate a new String:

Stream<String> sortedStream = validWordStream
      .map(s -> { char[] c = s.toCharArray(); 
                  Arrays.sort(c);
                  return new String(c);});
  • Related