The challenge

Santa’s senior gift organizer Elf developed a way to represent up to 26 gifts by assigning a unique alphabetical character to each gift. After each gift was assigned a character, the gift organizer Elf then joined the characters to form the gift ordering code.

Santa asked his organizer to order the characters in alphabetical order, but the Elf fell asleep from consuming too much hot chocolate and candy canes! Can you help him out?

Sort the Gift Code

Write a function called sortGiftCode that accepts a string containing up to 26 unique alphabetical characters, and returns a string containing the same characters in alphabetical order.

Examples (Input => Output):

1
2
3
"abcdef"                       => "abcdef"
"pqksuvy"                      => "kpqsuvy"
"zyxwvutsrqponmlkjihgfedcba"   => "abcdefghijklmnopqrstuvwxyz"

The solution in Java code

Option 1:

1
2
3
4
5
6
7
8
public class GiftSorter{
  public String sortGiftCode(String code){
    return code.chars()
      .sorted()
      .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
      .toString();
  }
}

Option 2:

1
2
3
4
5
6
7
public class GiftSorter{
  public String sortGiftCode(String code){
    char[] chars = code.toCharArray();
    java.util.Arrays.sort(chars);
    return new String(chars);
  }
}

Option 3:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import java.util.Arrays;
import java.util.stream.Collectors;

public class GiftSorter {
    public String sortGiftCode(String code) {
        return Arrays.stream(code.split(""))
            .sorted()
            .collect(Collectors.joining(""));
    }
}

Test cases to validate our solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class GiftSorterTest {
    @Test
    public void Tests1() throws Exception {
        GiftSorter gs = new GiftSorter();
        assertEquals("sort fedcba", "abcdef", gs.sortGiftCode("fedcba"));
    }
       
    @Test
    public void Tests2() throws Exception {
        GiftSorter gs = new GiftSorter();
        assertEquals("reverse alphabet", "abcdefghijklmnopqrstuvwxyz", gs.sortGiftCode("zyxwvutsrqponmlkjihgfedcba"));
    }
 
}