使用 Java 流处理字符串

Process string using Java streams

我需要一些指导。我不确定如何使用 Java Streams 将示例文本文件读入对象数组。流是否提供从文件中读取的字符串中正确输出字符位置的功能?

我正在使用 Java I/O 读取文件,然后将内容作为字符串传递给此函数以创建方块数组....

可以使用 Java 8 Stream 创建对象数组吗?如果是这样请如何。谢谢。

使用 java 流你可以这样做:

        AtomicInteger row = new AtomicInteger(-1);
        // count specific characters with this:
        AtomicInteger someCount = new AtomicInteger();
        try (Stream<String> stringStream = Files.lines(Paths.get("yourFile.txt"))) { // read all lines from file into a stream of strings

            // This Function makes an array of Square objects of each line
            Function<String, Square[]> mapper = (s) -> {
                AtomicInteger col = new AtomicInteger();
                row.incrementAndGet();
                return s.chars()
                        .mapToObj(i -> {
                            // increment counter if the char fulfills condition
                            if((char)i == 'M')
                                someCount.incrementAndGet();
                            return new Square(row.get(), col.getAndIncrement(), (char)i);
                        })
                        .toArray(i -> new Square[s.length()]);
            };

            // Now streaming all lines using the mapper function from above you can collect them into a List<Square[]> and convert this List into an Array of Square objects
            Square[][] squares = stringStream
                    .map(mapper)
                    .collect(Collectors.toList()).toArray(new Square[0][]);
        }

回答你的第二个问题:如果你有一个 Square[] 数组并且想找到第一个带有 val == 'M' 的 Square 你可以这样做:

Optional<Square> optSquare = Stream.of(squares).flatMap(Stream::of).filter(s -> s.getVal() == 'M').findFirst();

// mySquare will be null if no Square was matching condition
Square mySquare = optSquare.orElse(null);