手动创建一个文本文件 demo.txt,输入一段英文字符,编写一个
程序去统计输入的字符的个数,在屏幕上显示次数最多的字符和次数,
并显示统计所消耗的时间。
提 示 :java 获 取 当 前 的 时 间 可 以 使 用 System 类 中 类 方 法
currentTimeMillis()。
文件内容如下:
abccde
defghijjjj
测试代码如下:
public class Test {
public static void main(String[] args) throws SQLException, IOException {
long start = System.currentTimeMillis();
BufferedReader reader = new BufferedReader(new FileReader("/Users/zzuhkp/hkp/project/demo/target/demo.txt"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String content = sb.toString();
System.out.println("字符个数:" + content.length());
Arrays.stream(content.split("")).collect(Collectors.groupingBy(item -> item))
.entrySet().stream().max(Comparator.comparingInt(o -> o.getValue().size())).ifPresent(entry -> {
System.out.println("次数最多字符:" + entry.getKey());
System.out.println("次数:" + entry.getValue().size());
});
long cost = System.currentTimeMillis() - start;
System.out.println("耗时:" + cost + "ms");
}
}
测试结果如下:
字符个数:16
次数最多字符:j
次数:4
耗时:78ms
这个用字符流就可以,没必要用字节流吧。