Anagrams and Palindromes examples in Java 8
In this post:
- anagram example in Java
- check two words are they anagrams
- extract anagrams from list
- palindrome example
- palindrome - by using StringBuilder reverse method
- palindrome - with iteration
You can check also Anagrams and Palindromes in Python
Anagrams with Java 8
Anagrams are any words or sentences whose scrambled letters create a different word or phrase. Two strings, phrases or sentences are called anagrams if they contain same set of characters but in different order.
Several examples:
ASTRONOMER -> MOON STARER
ELEVEN PLUS TWO -> TWELVE PLUS ONE
DORMITORY -> DIRTY ROOM
Check two words if they are anagrams
Code example in Java checking if two words are anagrams:
public static void main(String[] args) {
System.out.println(isAnagram("face", "cafe"));
System.out.println(isAnagram("face", "caffe"));
}
public static Boolean isAnagram(String word1, String word2){
List<String> listWord1 = new ArrayList<>(Arrays.asList(word1.split("")));
List<String> listWord2 = new ArrayList<>(Arrays.asList(word2.split("")));
Collections.sort(listWord1);
Collections.sort(listWord2);
word1 = String.join("", listWord1);
word2 = String.join("", listWord2);
//return listWord1.equals(listWord2);
return word1.equals(word2);
//return word1 == word2 ; // not working because == tests for reference equality
}
What is doing this code.
- first we convert the words to lists of characters
- then lists are being sort in alphabetical order
- finally we convert the list back to string
- compare the result with method equals and return the result
result:
true
false
Extract anagrams from list:
Let say that you have a given list of words and you want to extract all groups of anagrams. Then you can use this code example in java:
public static void main(String[] args) {
List<String> wordList = Arrays.asList("face", "caffe", "cafe", "milk", "limk", "abc");
extractAnagrams(wordList);
}
public static void extractAnagrams(List<String> wordList){
Map<String,List<String>> map = new HashMap<>();
wordList.forEach(word -> map.put(anagramize(word), listWords(word, map) ));
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println("key : " + entry.getKey() + " word : " + entry.getValue());
}
System.out.println("Anagrams from list: " + wordList);
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
if(entry.getValue().size() > 1) {
System.out.println(entry.getValue());
}
}
}
public static String anagramize(String word){
List<String> listWord = new ArrayList<>(Arrays.asList(word.split("")));
Collections.sort(listWord);
return String.join("", listWord);
}
public static List<String> listWords(String word, Map<String,List<String>> map){
List<String> arrayList = map.getOrDefault(anagramize(word), new ArrayList<>(Arrays.asList()));
arrayList.add(word);
return arrayList;
}
the result of this code is:
key : iklm word : [milk, limk]
key : abc word : [abc]
key : aceff word : [caffe]
key : acef word : [face, cafe]
Anagrams from list: [face, caffe, cafe, milk, limk, abc]
[milk, limk]
[face, cafe]
Palindromes with Java 8
Palindrome is a word or phrase that reads the same way - backwards and forwards. Palindromes are anagrams which differs from an anagram because it requires specific order. Checking if a word is a palindrome is much easier than anagrams.
Examples:
- RADAR
- RACECAR
- CIVIC
- NOON
palindrome - by using StringBuilder reverse method
Sample java 8 code which is checking if a word is a palindrome:
public static void main(String[] args) {
System.out.println(isPalindrome("banana"));
System.out.println(isPalindrome("ana"));
}
public static Boolean isPalindrome(String word){
String rev = new StringBuilder(word).reverse().toString();
return word.equals(rev);
//return word == rev ; // not working because == tests for reference equality
}
result:
false
true
palindrome by iteration
You can use iteration if you want to check if a word is a palindrome or not. In the next example we are going to use numbers and show how to iterate and reverse a number:
public static void main(String[] args) {
System.out.println(numberPalindrome(1011));
System.out.println(numberPalindrome(10101));
}
public static Boolean numberPalindrome(int number){
int temp = number;
int rev = 0;
while(number>0) {
int dig = number % 10;
rev = rev * 10 + dig;
number = number/10;
}
return temp == rev;
}
result:
false
true