统计上网日志流量的Top3 :
package com.doit001.day1.example2;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
public class StreamCount {
public static void main(String[] args) throws Exception {
/**
* 加载配置文件 srcPath : 源文件路径
*/
Properties p = new Properties();
p.load(StreamCount.class.getClassLoader().getResourceAsStream("config.properties"));
String srcPath = p.getProperty("srcPath");
/**
* 把数据映射成: Map<域名(String), 总流量(Integer)>
*/
Map<String, Integer> mp = getUserStream(srcPath);
/**
* 按照总流量取出前三名Top3
*/
Map<String, Integer> sortByStream = sortByStream(mp);
sortByStream.forEach((k, v) -> System.out.println(k + " 总流量 : " + v));
}
/**
*
* @param srcPath : 源文件路径
* @return
*/
public static Map<String, Integer> getUserStream(String srcPath) {
HashMap<String, Integer> mp = new HashMap<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(srcPath), "UTF-8"))) {
String line;
while ((line = br.readLine()) != null) {
String[] split = line.split("\\s");// 按照空白切割每一行
// String phone = split[0];//无用数据
String urlStr = split[1];
Integer upStream = Integer.parseInt(split[2]);
Integer downStream = Integer.parseInt(split[3]);
String[] split2 = urlStr.split("\\.");// 切割urlStr,得到域名url
if (split2.length >= 3) {//过滤掉"坏文件"
String url = split2[1];
Integer sumStream = mp.getOrDefault(url, 0);
sumStream += upStream + downStream;
mp.put(url, sumStream);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return mp;
}
/**
* 取出总流量Top3
*
* @param mp
* 要排序的map集合
*/
public static Map<String, Integer> sortByStream(Map<String, Integer> mp) {
ArrayList<Entry<String, Integer>> list = new ArrayList<>(mp.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue().compareTo(o1.getValue()));
/**
* 将排好序的list存放到LinkedHashMap<String,Integer>,就可以按照想要的方式排序.
*/
LinkedHashMap<String, Integer> resMap = new LinkedHashMap<>();
/**
* 取出前三名Top3
*/
for (int i = 0; i < 3; i++) {
resMap.put(list.get(i).getKey(), list.get(i).getValue());
}
return resMap;
}
}