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?
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:
forEach
and mutate an external object.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With