简体   繁体   中英

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

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: 在此处输入图像描述

Question

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

since Array.sort 's return type is void , you can not use its value as map result.

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

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);});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM