将流中的行拆分为单词以映射它们的长度和值

Split lines from stream into words to map their length and value

根据给定的文本,通过使用流操作,我需要创建一个映射,其中单词长度是一个键,单词列表是一个值。我需要过滤掉不超过4个字符的单词。

String text = "random.txt";
Stream<String> lines = Files.lines(Paths.get(text))
Map<Integer,List<String>> map = lines.map(line -> line.split("[\s]+"))
                                .filter(word -> word.length > 4)
                                .collect(Collectors.groupingBy(
                                    word -> Integer.valueOf(word[0].length()),
                                    Collectors.mapping(word -> word[0], Collectors.toList()))
                                 );
                

我一定是理解错了,我使用过滤器的方式不起作用 - 抛出 IndexOutOfBoundsException。我应该如何排除长度少于 4 个字符的单词?

我只能弄清楚如何映射每行的第一个单词。我应该更改地图什么 每一个字? 谢谢!

 Map<Integer, List<String>> map = Stream.of("hello", "hell", "gun", "chicken", "building", "process", "world")
            .filter(pred -> pred.length() > 4)
            .collect(Collectors.groupingBy(String::length));

代码后的注释。

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.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Tester {
    private static Map<Integer, List<String>> byLines(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        try (Stream<String> lines = Files.lines(path)) {
            return lines.flatMap(line -> Arrays.stream(line.split("\s+")))
                        .filter(word -> word.length() > 4)
                        .collect(Collectors.groupingBy(word -> word.length()));
        }
    }

    public static void main(String[] args) {
        try {
            Map<Integer, List<String>> map = byLines("random.txt");
            map.forEach((key, value) -> System.out.printf("%d: %s%n", key, value));
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}

您需要调用方法 flatMap 来创建一个 Stream 来连接每行中的所有单词,从而将 Stream 行文本转换为单词流。

方法split(属于classString)returns一个数组。
方法 stream(属于 class Arrays)从数组创建一个 Stream
方法 flatMap 连接所有行中的所有单词并创建一个 Stream 包含文件 random.txt.
中的所有单个单词 然后你保留所有包含超过 4 个字符的单词。
然后你根据你的要求收集单词,即 Map 其中 [map] 键是长度, [map] 值是 List 包含所有具有相同长度的单词。