上网日志流量统计

统计上网日志流量的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;
}

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值