I have to get the most common ip from an logfile, I have a working method but I need some help with optimizing it/ I have to replace som passages with streams. Can you guys help me please ?
private static String mostCommonIp(String fileName) throws IOException
{
Map<String, Long> ipAppearanceCount = new HashMap<>();
String commonMostIp ="";
List<String> lines = Files.lines(Paths.get(fileName))
.collect(Collectors.toList());
List<String> ipAddresses = lines
.stream()
.map(line -> line.replaceAll("[ ]+", " ").split(" ")[2])
.collect(Collectors.toList());
for (int i = 0; i < ipAddresses.size(); i++) {
if (!ipAppearanceCount.containsKey(ipAddresses.get(i))){
ipAppearanceCount.put(ipAddresses.get(i), (long) 1);
}else{
ipAppearanceCount.put(ipAddresses.get(i),
ipAppearanceCount.get(ipAddresses.get(i))+1);
}
}
Comparator<? super Entry<String, Long>> maxValueComparator =
Comparator.comparing(Entry::getValue);
Optional<Entry<String, Long>> maxValue = ipAppearanceCount.entrySet()
.stream().max(maxValueComparator);
return String.valueOf(maxValue);
}