Skip to content

Instantly share code, notes, and snippets.

@wjlafrance
Last active August 29, 2015 13:57
Show Gist options
  • Save wjlafrance/9767527 to your computer and use it in GitHub Desktop.
Save wjlafrance/9767527 to your computer and use it in GitHub Desktop.
Rot13 in Java using Lambdas
package net.wjlafrance.lambdarot13;
import java.util.stream.Collectors;
/**
* Created by lafrance on 3/25/14.
*/
public class Main
{
/**
* Performs rot13 encoding using a functional paradigm. The string's characters are streamed, mapped to their
* rot13 value, and collected.
*/
private static String rot13functional(String s) {
return s.chars().mapToObj((c) -> String.valueOf((char) (
(c >= 'A' && c <= 'M') || (c >= 'a' && c <= 'm') ? (c + 13) :
(c >= 'N' && c <= 'Z') || (c >= 'n' && c <= 'z') ? (c - 13) : c))
).collect(Collectors.joining());
}
/**
* Performs rot13 encoding using an imperative paradigm. The string is iterated over, character by character. Each
* character is transformed and added to a StringBuffer.
*/
private static String rot13imperative(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c >= 'A' && c <= 'M') || (c >= 'a' && c <= 'm')) {
c += 13;
} else if ((c >= 'N' && c <= 'Z') || (c >= 'n' && c <= 'z')) {
c -= 13;
}
sb.append(c);
}
return sb.toString();
}
public static void main(String args[]) {
System.out.println(rot13functional("Hello world! Lambdas are awesome!"));
System.out.println(rot13imperative("Hello world! Lambdas are awesome!"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment