HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Find anagrams from a file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fromfileanagramsfind

Problem

The program reads words line by line from a file. It finds anagram groups and prints them in new line. Except for the GUI class, the anagram class takes 2ms.

I would like to be criticized in detail readability, correctness, efficiency, error handling and name convention.

And for potential question: if a data set is much larger, how will my application cope with it?

```
public class Anagram{

List> anagramGroupList = null;

public List> findAnagrams(String filePath) throws FileNotFoundException {

try {
// Open the file
FileInputStream inputStream = new FileInputStream(filePath);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
Map> anagramMap = new HashMap>();
String word;

// Read File Line By Line
while ((word = bufferedReader.readLine()) != null) {
// Sort characters of word
String sortedWord = sorting(word);

/*
* Use sorted word as a key for map
* If map contains key, add the list
* If not, create a new anagram list and add list with key
*/
if (!anagramMap.containsKey(sortedWord))
anagramMap.put(sortedWord, new ArrayList());

anagramMap.get(sortedWord).add(word);
}

anagramGroupList = new ArrayList>(anagramMap.values());

bufferedReader.close();

} catch (IOException e) {

e.printStackTrace();
}

return anagramGroupList;

}

// Sort alphabetically characters of given word
private static String sorting(String word) {
char[] sortedChars = word.toCharArray();
Arrays.sort(sortedChars);
return new String(sortedChars);

Solution

The method findAnagrams dealing with filePaths, InputStreams and FileNotFoundException is a code smell for me. I expect a method with the name findAnagrams to work with words.

Actually, your Anagram class dealing with Files, InputStreams etc, breaks the SRP. You should extract a class out of the Anagram class that handles the IO responsibility. The separation makes the classes simpler and more flexible to change.

Context

StackExchange Code Review Q#153863, answer score: 3

Revisions (0)

No revisions yet.