Add space as line break using Java 8 thread (lambdas)

I am writing an Xor method that ecnrypts some string, adding (like xor operators) random values ​​to its characters. The result should look like a string with hexadecimal values ​​of encrypted characters.

Example:

"Hello world" => "0006F 00046 00066 00076 0004D 0007F 00047 0007D 00062 0006E"

Code:

StringBuilder sb = new StringBuilder();

inputText.chars()                                      // get char stream
         .filter(c -> c != ' ')                         // remove spaces
         .map(c -> c ^ random.nextInt(randBound))       // do xor for each char
         .boxed()                                       // to Integer stream
         .map(i -> String.format("%05X ", i & 0xFFFFF)) // to Hex String values
         .forEach(sb::append);

if (sb.length() > 0)
    sb.deleteCharAt(sb.length() - 1);

return sb.toString();

As you can see, I generated the result as "%05X ", so I got unwanted space at the end of the line. And you need to use sb.deleteCharAt(sb.length() - 1);.

How to format the correct result directly in the stream?

+4
source share
1

Stream . , Collectors.joining(delimiter):

inputText.chars() // get char stream
         .filter(c -> c != ' ') // remove spaces
         .map(c -> c ^ random.nextInt(randBound)) // do xor for each char
         .mapToObj(i -> String.format("%05X", i & 0xFFFFF)) // to Hex String values
         .collect(joining(" "));  // join each value together, separated with a space

, :

  • forEach .
  • .
+6

Source: https://habr.com/ru/post/1613016/


All Articles