要求
1.数据不能一次读取到内存中,否则直接用HashMap统计IP出现的频率(IP为key,次数为value),然后按照次数排序就可以实现了;
2.不借助数据库存储数据;
3.使用hash拆分。
实现思路
这道题的做法是先对文件遍历一遍,将访问百度的各个IP分别记录到单独的子文件中,然后利用HashMap统计每个文件中IP的访问次数,分别找到每个文件中访问次数最高的IP,再从这些IP中找到整体频率最高的IP。
代码实现
如以下例子中,访问百度次数最多的IP为192.168.1.1和192.168.1.2,访问频率分别为两次。
package com.alex.examples;
import cn.hutool.core.io.FileUtil;
import java.io.File;
import java.util.*;
public class HashTest {
static int HASHLEN = 1000;
public static void main(String[] args) {
String folderUrl = "D:\\test\\baidu.com"; //文件夹的路径
String words[] = {"192.168.1.1", "192.168.1.2", "192.168.1.1", "192.168.1.3", "192.168.1.4", "192.168.1.2"}; //模拟访问百度的ip数据集合
//拆封内容
for (String word : words) {
int temp = hash(word.toCharArray());
String fileUrl = folderUrl + "\\" + temp + ".txt";
Boolean isExist = FileUtil.exist(fileUrl);
if (!isExist) {
FileUtil.touch(fileUrl);
}
FileUtil.appendUtf8String(word + "\r\n", fileUrl);
}
//读取各个子文件的内容
Map<String, Integer> fileMap = new HashMap<>();
List<File> loopFiles = FileUtil.loopFiles(folderUrl);
for (File loopFile : loopFiles) {
List<String> list = FileUtil.readLines(loopFile, "UTF-8");
for (int i = 0; i < list.size(); i++) {
String content = list.get(i); //正文,作为key使用
if (!fileMap.containsKey(content)) {
fileMap.put(content, 1);
} else {
Integer count = fileMap.get(content) + 1;
fileMap.put(content, count);
}
}
}
//遍历fileMap集合,获取文件中出现频率最高的词汇
Map<String, Integer> newFileMap = getMaxStr(fileMap);
for (Map.Entry<String, Integer> m : newFileMap.entrySet()) {
System.out.println("访问百度次数最多的IP:" + m.getKey() + ",访问频率:" + m.getValue());
}
}
/**
* hash切分法,计算每个ip对应于的区间值
*
* @param word
* @return
*/
public static int hash(char[] word) {
int index = 0;
int i = 0;
while (i < word.length) {
index += index * 31 + word[i];
i++;
}
return index % HASHLEN;
}
/**
* Map 中获取最大值 Value 和对应的 Key
*
* @param map
* @return
*/
public static Map<String, Integer> getMaxStr(Map<String, Integer> map) {
int maxV = 0;
String maxK;
//临时值,保存每次最大值键,下个值比他大就将他替掉,换成新值
String maxKRemove = null;
Map<String, Integer> newMap = new TreeMap();
Iterator keys = map.keySet().iterator();
while (keys.hasNext()) {
Object key = keys.next();
maxK = key.toString();
int value = Integer.parseInt(map.get(key).toString());
if (value > maxV) {
if (null != maxKRemove) {
newMap.clear();
}
maxV = value;
newMap.put(maxK, maxV);
maxKRemove = maxK;
} else if (value == maxV) {
newMap.put(maxK, maxV);
}
}
return newMap;
}
}