I have a question. So lets say I have about 10 different string types, and I need to write a method where depending on if the strings are anagrams, they are grouped together. Whats the best way to approach this? 2D arrays?
I obviously have other methods that compare the strings and determine whether they are anagrams. This question is solely to ask how do I approach this problem of sorting different strings in different groups.
List example: -Dog -Bread -Africa -God -Dreab -dGO -Treat -dabre -trate -China
Group 1: Dog, god, dGO
Group 2: Bread, Dreab, dabre
Group 3: Africa
Group 4: Treat, trate
Group 5: China
One way to do it is to create a Map<String,List<String>>. All anagrams of the same letters sort to the same sorted string. So that string would be your key to the map. The List portion would be the actual anagrams.
so acne and cane would be
acen => [acne, cane]
To sort the anagram you need to split the string into letters and then use either Arrays.sort or Collections.sort. Then put the letters back together.