Skip to content

How to Sort the Gift Code in Java

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):

"abcdef" => "abcdef" "pqksuvy" => "kpqsuvy" "zyxwvutsrqponmlkjihgfedcba" => "abcdefghijklmnopqrstuvwxyz"
Code language: PHP (php)

The solution in Java code

Option 1:

public class GiftSorter{ public String sortGiftCode(String code){ return code.chars() .sorted() .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); } }
Code language: Java (java)

Option 2:

public class GiftSorter{ public String sortGiftCode(String code){ char[] chars = code.toCharArray(); java.util.Arrays.sort(chars); return new String(chars); } }
Code language: Java (java)

Option 3:

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("")); } }
Code language: Java (java)

Test cases to validate our solution

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")); } }
Code language: Java (java)

See also  Base-2 in Java
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x