Skip to content

Instantly share code, notes, and snippets.

@emoran
Created October 23, 2022 16:27
Show Gist options
  • Save emoran/d31bcc91ef79ebf61bf67e31dbe0c4ee to your computer and use it in GitHub Desktop.
Save emoran/d31bcc91ef79ebf61bf67e31dbe0c4ee to your computer and use it in GitHub Desktop.
Group Anagram words in Salesforce Apex.
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