使用Java流处理字符串内容

问题描述 投票:0回答:1

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

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

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

java java-8 java-stream maze
1个回答
-1
投票

使用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);
© www.soinside.com 2019 - 2024. All rights reserved.