Created
October 23, 2022 16:27
-
-
Save emoran/d31bcc91ef79ebf61bf67e31dbe0c4ee to your computer and use it in GitHub Desktop.
Group Anagram words in Salesforce Apex.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<String> listWords = new List<String>{'bored','robed','cat','act','tac','eme'}; | |
Map<String,List<String>> mapWords = new Map<String,List<String>>(); | |
for(String word: listWords){ | |
List<String> splittedWord = word.split(''); | |
splittedWord.sort(); | |
String wordNew = ''; | |
for(String newWord:splittedWord){ | |
wordNew += newWord; | |
} | |
if(mapWords.containsKey(wordNew)){ | |
List<String> words = mapWords.get(wordNew); | |
words.add(word); | |
mapWords.put(wordNew, words); | |
} | |
else{ | |
mapWords.put(wordNew,new List<String>{word}); | |
} | |
} | |
System.debug(mapWords.values()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment