使用Java流处理字符串

huangapple go评论73阅读模式
英文:

Process string using Java streams

问题

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

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

这是否可以使用Java 8 Stream来创建对象数组?如果可以,怎么做?谢谢。

英文:

I am in need of some guidance. I am not sure how to go about reading in the sample text file into an array of objects using Java Streams. Does stream provide a functionality to correctly output a position of the character from a string that it reads from the file?

I am reading a file using Java I/O and then passing the content as string to this function to create array of Squares....

Can this creation of Array of Objects be done using Java 8 Stream ? If so How please. Thank you.

答案1

得分: -1

使用Java Streams,您可以像这样进行操作:

        AtomicInteger row = new AtomicInteger(-1);
        // 使用这个来计算特定字符的数量:
        AtomicInteger someCount = new AtomicInteger();
        try (Stream<String> stringStream = Files.lines(Paths.get("yourFile.txt"))) { // 从文件中读取所有行到字符串流中

            // 这个函数创建了每一行的Square对象数组
            Function<String, Square[]> mapper = (s) -> {
                AtomicInteger col = new AtomicInteger();
                row.incrementAndGet();
                return s.chars()
                        .mapToObj(i -> {
                            // 如果字符满足条件,增加计数器
                            if((char)i == 'M')
                                someCount.incrementAndGet();
                            return new Square(row.get(), col.getAndIncrement(), (char)i);
                        })
                        .toArray(i -> new Square[s.length()]);
            };

            // 使用上面的映射函数对所有行进行流式处理,您可以将它们收集到List<Square[]>中,然后将此List转换为Square对象的数组
            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();

// 如果没有匹配条件的Square,mySquare将为null
Square mySquare = optSquare.orElse(null);
英文:

Using java streams you could do something like this:

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

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

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

Answering your second question: If you have an array of Square[] and want to find the first Square with val == 'M' you could do this:

Optional&lt;Square&gt; optSquare = Stream.of(squares).flatMap(Stream::of).filter(s -&gt; s.getVal() == &#39;M&#39;).findFirst();

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

huangapple
  • 本文由 发表于 2020年4月7日 02:12:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/61066223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定