Pig latin translator

The problem

Write a program that reads a sentence as input and converts each word to Pig latin. Pig Latin is a constructed language game in which words in English are altered according to a simple set of rules. In this exercise, convert the word by removing the first letter, placing the that letter at the end of the word, and then appending "ay" to the word. Here is an example:

  • English: I SLEPT MOST OF THE NIGHT
  • Pig Latin: IAY LEPTSAY OSTMAY FOAY HETAY IGHTNAY

Breaking it down

For this exercise we will use a popular third party library created by Google called guava. We will ask for the user to enter in the sentence and then split the string on whitespace. Next we will use the java 8 intermediate operation map four times. First to trim each string, second to convert string to upper case, third to move the first char to the end and finally to append the "AY". That last operation on the stream is to collect values into a list. Since have each element of the sentence in a list, we will use java 8 to join strings separated by a space. To learn more about function visit java 8 function example.

public static void main(String[] args) {
    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    // Ask user to enter a string to translate
    System.out.println("Enter a string to translate to Pig Latin.");
    System.out.print("> ");
    String input = keyboard.nextLine();

    // close the keyboard
    keyboard.close();

    List<String> elementsInString = Lists.newArrayList(Splitter.on(" ")
            .split(input));

    Function<String, String> swapFirstLastChar = new Function<String, String>() {
        @Override
        public String apply(String s) {
            if (s.length() <= 1) {
                return s;
            } else {
                return s.substring(1, s.length()) + s.charAt(0);
            }
        }
    };

    List<String> translatedString = elementsInString.stream()
            .map(String::trim).map(String::toUpperCase)
            .map(swapFirstLastChar).map((String s) -> {
                return s + "AY";
            }).collect(Collectors.toList());


    System.out.println("Translated sentence is: "
            + String.join(" ", translatedString));
}

Output

Enter a string to translate to Pig Latin.
> I SLEPT MOST OF THE NIGHT
IAY LEPTSAY OSTMAY FOAY HETAY IGHTNAY

Level Up

  • Take the swapFirstLastChar and make it an inline function
  • Create unit test to validate input and output