During an interview I was asked to consider the following:
You are trying to find an instance of an error code within a number of log files within a directory. The goal is to count the number of times that the error code appears within the specified files.
For the written function, it was to be passed the following arguments (the directory and general file naming convention were known):
[TimeStamp]: String
[ErrorCode]: String
Afterward I went home and coded up a basic implementation of a single file search algorithm with, I believe, O(1) search time after the files are parsed. Does this implementation make sense, and is it correct in terms of Java 8?
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by Brendan on 5/13/2016.
*
* A quick implementation of an interview File Search algorithm.
* Parses the file into a hash map so that occurrences of a phrase
* can be quickly looked up.
*/
public class FileSearch {
public static void main(String[] args) {
Map<String, Long> wordMap = new HashMap<>();
try {
wordMap = populateWordMap("C:\\Projects\\logs\\app-log.log");
} catch(IOException e) { }
System.out.println("Total unique words found: " + wordMap.size());
System.out.println("Most popular word: " + findMostPopularWord(wordMap));
}
private static String findMostPopularWord(Map<String, Long> wordMap) {
return wordMap.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.get().getKey();
}
private static Map<String, Long> populateWordMap(String filePath) throws IOException {
return Files.lines(Paths.get(filePath))
.map((wholeLine) -> wholeLine.split(" "))
.map((lineArray) -> mapWordsInLine(lineArray))
.map(Map::entrySet)
.flatMap(Collection::stream)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (m1, m2) -> m1 + m2));
}
private static Map<String, Long> mapWordsInLine(String[] lineArray) {
return Arrays.stream(lineArray)
.collect(Collectors.groupingBy(String::toString, Collectors.counting()));
}
}
For the written function, it was to be passed the following arguments (the directory and general file naming convention were known):
Where is this function? You are doing a different thing from the asked. You get the most popular word but you never return the count ofErrorCode
\$\endgroup\$grep
orawk
". \$\endgroup\$