Java 优雅的处理文件

好多人觉得 Java 的 IO 死难用,贼恶心,大概率是因为学习的和搜索出来的结果都是上个时代的写法,那一连串的 xxxStream 确实是够恶心,我来 Show 一下 JDK 8 怎么处理文件。

比如一个简单的面试题

文件里每行有多个单词,由空格分隔,统计输出单词次数最多的 10 个单词和次数

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {
        String file = "word.txt";
        Map<String, Integer> wordCountMap = new HashMap<>();

        Files.lines(Paths.get(file))
                .forEach(line -> {
                    String[] words = line.split(" ");
                    for (String word : words) {
                        wordCountMap.merge(word.trim(), 1, Integer::sum);
                    }
                });
        wordCountMap.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .skip(wordCountMap.size() - 10)
                .forEach(System.out::println);
    }
}
java-8·java
216 views
Comments
登录后评论
Sign In
·

代码可以高亮:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {
        String file = "word.txt";
        Map<String, Integer> wordCountMap = new HashMap<>();

        Files.lines(Paths.get(file))
                .forEach(line -> {
                    String[] words = line.split(" ");
                    for (String word : words) {
                        wordCountMap.merge(word.trim(), 1, Integer::sum);
                    }
                });
        wordCountMap.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .skip(wordCountMap.size() - 10)
                .forEach(System.out::println);
    }
}