使用Java流将String内容直接处理为{col,row和value}的对象数组吗?

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

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

我有一个对象。

public class Square {
protected int row;
protected int column;
protected char val;
protected Square(int row, int column, char val) {
....
}

}

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

`public static Square[][] buildFromString(input){
        String[] lines = input.split("[\r]?\n");
        int height = lines.length;
        int width = lines[0].length();
        int count = 0;
        Square[][] squares = new Square[height][width];

        for (int row = 0; row < height; row++) {
            for (int col = 0; col < width; col++) {
                Square square = new Square(row, col, lines[row].charAt(col));
                squares[row][col] = square;
                  if (square.val() == 'M')
                      count++;
            }
        }
 ...
 }`

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

编辑:第二个问题

    for (int i = 0 ; i < 10; i ++) {
            for (int j = 0; j < 16; j++) {
                Square s = getSquare(i, j);
                if (s.getVal() == 'M')
                    return s;
            }
        }
     return null;
    }
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.