C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
GetSortedLine: This method takes the characters in a string and sorts them with Arrays.sort. It returns a new string—it generates keys.
ArrayListAnagramsFor: This accesses the HashMap and sees if an ArrayList of original words exists. It prints all anagrams for a certain string.
Main: Reads in the text file of words. We generate sort keys and build up the HashMap data structure.
Java program that finds anagrams
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class Program {
static HashMap<String, ArrayList<String>> _map;
static String getSortedLine(String line) {
// Get letters and sort them.
char[] letters = line.toCharArray();
Arrays.sort(letters);
return new String(letters);
}
static void listAnagramsFor(String word) {
// Sort the letters.
String sortedLetters = getSortedLine(word);
// Get list from the sorted key in the HashMap.
if (_map.containsKey(sortedLetters)) {
ArrayList<String> list = _map.get(sortedLetters);
// Display items.
for (String item : list) {
System.out.println(item);
}
}
}
public static void main(String[] args) throws IOException {
_map = new HashMap<String, ArrayList<String>>();
// Read words file.
BufferedReader reader = new BufferedReader(
new FileReader("C:\\enable1.txt"));
// Read all lines.
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
// Get sorted line.
String sortedLine = getSortedLine(line);
// Add line with the sorted key to the HashMap.
// ... Each value is an ArrayList.
if (_map.containsKey(sortedLine)) {
_map.get(sortedLine).add(line);
} else {
// Create new ArrayList at key.
ArrayList<String> list = new ArrayList<>();
list.add(line);
_map.put(sortedLine, list);
}
}
// Close file.
reader.close();
// Get anagrams.
System.out.println("Anagrams for senator:");
listAnagramsFor("senator");
}
}
Output
Anagrams for senator:
atoners
senator
treason
And: The HashMap uses more memory. For the lowest-memory approach, we could test a string against all words in the original file.
HashMapFurther: A tree like a DAG that stores each letter would provide optimal performance for this operation, but is more complex.
TreeSo: Anagrams are a useful exercise. The Java program here is not optimal—see if you can improve it.