如何使用 Java Stream 功能 - 如果要在循环内执行多个语句: 代码片段:
PDAcroForm pdAcroForm = pdfDocument.getDocumentCatalog().getAcroForm();
JSONObject jsonData = new JSONObject(pdfdata);
String[] specialChars = {" ", "-", ".", "(", ")", "/", "*"};
String[] specialCharsReplaceWith = {"_", "_1_", "_2_", "_3_", "_4_", "_5_", "_6_"};
for (PDField pdField : pdAcroForm.getFields()) {
String fieldName = pdField.getFullyQualifiedName();
System.out.println("fieldName:" + fieldName);
for(int i = 0; i < specialChars.length; i++) {
fieldName = fieldName.trim().replace(specialChars[i], specialCharsReplaceWith[i]);
}
if(StringUtils.isNotEmpty(fieldName)) {
fieldName = fieldName.substring(0, 1).toLowerCase().concat(fieldName.substring(1));
}
if (jsonData.has(fieldName)) {
String value = jsonData.getString(fieldName);
pdField.setValue(value);
pdField.setReadOnly(true);
}
}
有什么建议吗?
是的,由于您最终需要
PDFField
和生成的 json 字段名称,因此 Stream 似乎不合适。我会让它看起来像
pdAcroForm.getFields().forEach(pdField -> {
Optional.of(jsonFieldMapper.getFieldName(pdField))
.filter(jsonData::has)
.map(jsonData::getString)
.ifPresent(jsonValue -> {
pdField.setValue(jsonValue);
pdField.setReadOnly(true);
});
});
并将整个替换和子字符串提取到
jsonFieldMapper
中。