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.

Revisions

  1. emoran created this gist Oct 23, 2022.
    24 changes: 24 additions & 0 deletions anagramGrouped.apex
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    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());