我有一个像这样的for循环。
for (int i = 0; i < filePaths.size(); i++) {
String filePath = filePaths.get(i);
Mat mat = Imgcodecs.imread(filePath);
Mat gray = new Mat();
cvtColor(mat, gray, 6);
if (i != filePaths.size()-1) {
threshold(gray, gray, 150, 255, THRESH_TRUNC);
}
Imgcodecs.imwrite(filePath, gray);
}
是否可以将其转换为声明性代码。
谢谢。
最佳答案
我想您想在应用程序中使用某种函数式风格,并将这种命令式代码风格删除为函数式代码风格?
所以,如果我理解正确的话,你应该采取一些额外的行动。首先,您必须创建 DTO(数据传输对象)来传递这部分逻辑。
String filePath = filePaths.get(i);
Mat mat = Imgcodecs.imread(filePath);
您创建此 DTO:
class FilePathDTO {
private final String filepath;
private final Mat mat;
private final Mat grey = new Mat();
private final boolean isNotLastFilepath;
public FilePathDTO(String filepath, Mat mat, boolean isLast) {
this.filepath = filepath;
this.mat = mat;
this.isNotLastFilepath = isLast;
}
public String getFilepath() {
return filepath;
}
public Mat getMat() {
return mat;
}
public Mat getGrey() {
return grey;
}
public boolean isNotLastFilepath() {
return isNotLastFilepath;
}
}
然后,代码将如下所示:
filePaths.stream()
.map(filePath -> new FilePathDTO(filePath, Imgcodecs.imread(filePath), filePaths.indexOf(filePath) != filePaths.size() - 1))
.forEach(dto -> {
cvtColor(dto.getMat(), dto.getGrey(), 6);
if(dto.isNotLastFilepath) {
threshold(dto.getGrey(), dto.getGrey(), 150, 255, THRESH_TRUNC);
}
Imgcodecs.imwrite(dto.getFilepath(), dto.getGrey());
});
但是,你会产生一些副作用,例如
if(dto.isNotLastFilepath) {
threshold(dto.getGrey(), dto.getGrey(), 150, 255, THRESH_TRUNC);
}
而且你根本无法摆脱命令式代码风格。您可以使您的代码更接近功能。
关于java - 函数式编程将代码转换为声明式风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56215031/