我需要一些指导。我不确定如何使用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完成对象数组的创建吗?如果是这样,请。谢谢。
##########
# #
# ### ## #
# # # #
编辑:在这里为大家添加:正方形加载到2D Squares [] []数组中,也可以在这里使用...此函数可检索特定的Square ...我尝试了IntStream,但没有运气。如果可以在不使用getSquare()的情况下直接执行此操作,则内存中有一个Squares [] []。
public Square getSquare(char val) {
for (int i = 0 ; i < 15; i ++) {
for (int j = 0; j < 20; j++) {
Square s = getSquare(i, j);
if (s.getVal() == val)
return s;
}
}
return null;
}
使用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][]);
}
使用Java流,您可以执行以下操作: