gpt4 book ai didi

java - 将几个 Java 循环替换为一个简单的 lambda,但看起来过于复杂

转载 作者:太空宇宙 更新时间:2023-11-04 09:55:11 24 4
gpt4 key购买 nike

我正在处理一些 apache POI 文件,它正在工作,并且我正在对此进行一些重构,但我对这段代码面临疑问:

for (XWPFTable tbl : doc.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph paragraph : cell.getParagraphs()) {
for (XWPFRun xwpfRun : paragraph.getRuns()) {
String text = xwpfRun.getText(0);
if (text != null && text.contains(key)) {
text = text.replace(key, replaces.get(key) == null ? "" : replaces.get(key));
xwpfRun.setText(text, 0);
}
}
}
}
}
}

当我尝试将其替换为 lambda 时,代码如下所示:

    List<XWPFRun> collect = doc.getTables().stream().flatMap(xwpfTable -> xwpfTable.getRows().stream()
.flatMap(xwpfTableRow -> xwpfTableRow.getTableCells().stream().
flatMap(xwpfTableCell -> xwpfTableCell.getParagraphs().stream()
.flatMap(xwpfParagraph -> xwpfParagraph.getRuns().stream().filter(Objects::nonNull)))))
.collect(Collectors.toList());

对我来说,这段代码非常复杂,因为它不会返回任何我需要为每个最后一个拆分的内容:

 for (XWPFRun xwpfRun : paragraph.getRuns()) {
String text = xwpfRun.getText(0);
if (text != null && text.contains(key)) {
text = text.replace(key, replaces.get(key) == null ? "" : replaces.get(key));
xwpfRun.setText(text, 0);
}
}

我很确定有一个更好、更干净的方法来做到这一点,但我无法弄清楚,你有一些想法吗?

最佳答案

您已经非常接近可读的解决方案了。

您可以像这样“展平”您的 flatMap 调用:

doc.getTables().stream()
.map(XWPFTable::getRows).flatMap(List::stream)
.map(XWPFTableRow::getTableCells).flatMap(List::stream)
.map(XWPFTableCell::getParagraphs).flatMap(List::stream)
.map(XWPFParagraph::getRuns).flatMap(List::stream)
.filter(Objects::nonNull)
.forEach(xwpfRun -> {
String text = xwpfRun.getText(0);
if (text != null && text.contains(key)) {
text = text.replace(key, replaces.get(key) == null ? "" : replaces.get(key));
xwpfRun.setText(text, 0);
}
});

或者您可能更愿意将每个 .map().flatMap() 替换为单个 .flatMap,这看起来更像您的解决方案。例如:

.flatMap(table -> table.getRows().stream())
.flatMap(row -> row.getTableCells().stream())
...

您还可以在 forEach 中添加 .filter 而不是 if 语句,但在我看来,这看起来更复杂。

关于java - 将几个 Java 循环替换为一个简单的 lambda,但看起来过于复杂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54237313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com