簡體   English   中英

使用 Java 流處理字符串

[英]Process string using Java streams

我需要一些指導。 我不確定如何使用 Java Streams 將示例文本文件讀入對象數組中。 stream 是否提供從文件中讀取的字符串中正確 output a position 的功能?

我正在使用 Java I/O 讀取文件,然后將內容作為字符串傳遞給此 function 以創建 Squares 數組....

可以使用 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM