Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add space as split to strings using Java 8 stream (lambdas)

I'm writing a Xor method which ecnrypts some string by adding (as xor operation) random values to its characters. Result should look like as string with hex values of encrypted characters.

Example:

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

The 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 see, I've formated the result as "%05X ", so I've got unwanted space in the end of string. And need to use sb.deleteCharAt(sb.length() - 1);.

How to format the correct result directly in stream?

like image 643
Letfar Avatar asked Feb 09 '23 17:02

Letfar


1 Answers

What you want is to collect elements of a Stream into a String. This can be done using 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

This has the benefit that:

  • There's no need to use forEach and mutate an external object.
  • There's no need to delete the last character.
like image 134
Tunaki Avatar answered Feb 11 '23 13:02

Tunaki