4

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?

2 Answers 2

8

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.