用path和files写的英文单词统计的JAVA的代码怎么写
时间: 2024-05-09 10:17:11 浏览: 16
以下是使用 path 和 files 写的英文单词统计的 Java 代码示例:
```
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
public class WordCounter {
public static void main(String[] args) throws IOException {
Path path = Paths.get("file.txt"); // 替换为要统计的文件路径
try (Stream<String> lines = Files.lines(path)) {
Map<String, Integer> wordCounts = new HashMap<>();
lines.flatMap(line -> Arrays.stream(line.trim().split("\\s+")))
.forEach(word -> wordCounts.merge(word, 1, Integer::sum));
wordCounts.forEach((word, count) -> System.out.println(word + ": " + count));
}
}
}
```
这段代码首先使用 `Paths.get()` 方法创建一个 `Path` 对象,表示要统计的文件路径。注意,这里需要替换为实际的文件路径。
然后使用 `Files.lines()` 方法读取文件中的所有行,并将其转换为一个 `Stream<String>` 对象。接下来,通过 `flatMap()` 方法将每行拆分为独立的单词,并通过 `forEach()` 方法将每个单词和计数器存储到一个 `Map<String, Integer>` 对象中。
最后,使用 `forEach()` 方法遍历 `Map` 中的所有键值对,输出每个单词和其出现次数。
请注意:这段代码只是一个简单的示例,可能需要根据实际情况进行调整和优化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)