大日志文件中如何统计单词个数?及map按value排序lambda表达式版
2017-05-19 21:13
274 查看
package com.nys.countwords;
import java.io.File;
import java.io.IOException;
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.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CountPaser {
private Map<String, Integer> countMap=new HashMap<>();
public void parse(String logPath) throws IOException {
Pattern pattern = Pattern.compile("(?i)[a-z]+");
Matcher matcher=null;
Scanner scanner=new Scanner(new File(logPath));
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
matcher = pattern.matcher(line);
while(matcher.find()) {
String word = matcher.group();
if(null==countMap.get(word)) {
countMap.put(word, 1);
}else {
countMap.put(word, countMap.get(word)+1);
}
}
}
scanner.close();
}
public static void main(String[] args) {
CountPaser cp = new CountPaser();
try {
cp.parse("nys.log");
} catch (IOException e) {
e.printStackTrace();
}
Map<String, Integer> map = cp.countMap;
Map sortMap = CountPaser.sortMap(map);
System.out.println(sortMap);
}
/**
* 对map中的数据按照value排序
*/
public static Map sortMap(Map<String, Integer> oldMap) {
ArrayList<Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(oldMap.entrySet());
Collections.sort(list, (x,y)->x.getValue().compareTo(y.getValue()));//java8特性 lambda表达式
LinkedHashMap<String,Integer> newMap = new LinkedHashMap<String,Integer>();
for(int i=0;i<list.size();i++) {
newMap.put(list.get(i).getKey(), list.get(i).getValue());
}
return newMap;
}
}
相关文章推荐
- 『转』统计一个日志文件里,单词出现频率的shell脚本
- 没有备份、只有归档日志,如何恢复数据文件?
- 如何减少日志文件的空间
- 如何缩小MS SQL Server日志文件
- 如何统计出一篇文章出现的文字个数? (高级) (使用std::map)
- 没有日志,只有MDF文件如何恢复数据库(转)[
- 如何使Microsoft SQL Server的日志文件不会增大
- 统计文件的单词数
- 如何彻底清除本地和远程系统日志文件
- 当有多个SiteMap文件时,如何让SiteMapDataSource选择特定的SiteMap文件
- 如何正确处理SQL SERVER日志文件
- 也谈如何缩小SQL SERVER日志文件
- 如何缩小MSSQL中巨大的事务日志文件
- 没有备份、只有归档日志,如何恢复数据文件?
- 如何删除SQL SERVER 2000的日志文件空间
- 如何缩小SQL SERVER日志文件
- 如何恢复没有日志文件的数据库的方法
- 请问如何从日志文件中读出其内容
- 如何清空数据库日志文件?
- 如何使Microsoft SQL Server的日志文件不会增大