BAEL-2144 sort string alphabetically

This commit is contained in:
Denis 2018-08-28 17:28:41 +02:00
parent 913ec96209
commit b2644c5cfc
3 changed files with 86 additions and 0 deletions

View File

@ -0,0 +1,29 @@
package com.baeldung.sorting.string.anagram;
import java.util.Arrays;
public class AnagramValidator {
public static boolean isValid(String text, String anagram) {
text = prepare(text);
anagram = prepare(anagram);
String sortedText = sort(text);
String sortedAnagram = sort(anagram);
return sortedText.equals(sortedAnagram);
}
private static String sort(String text) {
char[] chars = prepare(text).toCharArray();
Arrays.sort(chars);
return new String(chars);
}
private static String prepare(String text) {
return text.toLowerCase()
.trim()
.replaceAll("\\s+", "");
}
}

View File

@ -0,0 +1,26 @@
package org.baeldung.java.sorting.string;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.Test;
import com.baeldung.sorting.string.anagram.AnagramValidator;
class AnagramValidatorUnitTest {
@Test
void givenValidAnagrams_whenSorted_thenEqual() {
boolean isValidAnagram = AnagramValidator.isValid("Avida Dollars", "Salvador Dali");
assertTrue(isValidAnagram);
}
@Test
void givenNotValidAnagrams_whenSorted_thenNotEqual() {
boolean isValidAnagram = AnagramValidator.isValid("abc", "def");
assertFalse(isValidAnagram);
}
}

View File

@ -0,0 +1,31 @@
package org.baeldung.java.sorting.string;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class SortStringUnitTest {
@Test
void givenString_whenSort_thenSorted() {
String abcd = "bdca";
char[] chars = abcd.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
assertThat(sorted).isEqualTo("abcd");
}
@Test
void givenString_whenSortJava8_thenSorted() {
String sorted = "bdca".chars()
.sorted()
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
assertThat(sorted).isEqualTo("abcd");
}
}