我有一个 3 层的 java 对象。
该场景有几个部分:
public class Scenario {
private String scenarioId;
private List<Section> sectionList;
每个部分内都有几个标签:
public class Section {
private String sectionName;
private List<String> labelList;
我想将3层数据组装成一个字符串,例如:
<Scenario>
<section1>
<label11 data>
<label12 data>
<section2>
<label21 data>
<label22 data>
...
我有如下代码来选择每一层的参数,但如何将其组装成一个字符串:
String scenarioId = scenario.getScenarioId();
List<Section> sectionList = scenario.getSectionList();
sectionList.forEach(section -> {
String sectionName = section.getSectionName();
List<String> labelList = section.getLabelList();
String data;
if(!labelList.isEmpty()) {
data =copy.LabelData(labelList, input);
}
});
return scenario;
最佳答案
我猜想缺少一些代码或任何东西,但我假设您拥有所有 getter 和 setter,并且您希望像示例中那样在 lambda 中构建字符串。您只需使用 StringBuilder
或 StringBuffer
即可。但您要将其设为final
,以便可以在 lambda 中使用它。
final StringBuilder sb = new StringBuilder(scenario.getScenarioID());
sb.append("\n");
scenario.getSectionList().
// This filter has the same function as your if statement
.filter(section -> !section.getLabelList().isEmpty())
.forEach(section -> {
sb.append("\t");
sb.append(section.getSectionName());
sb.append("\n");
section.getLabelList().forEach(label -> {
sb.append("\t\t");
sb.append(label);
sb.append("\n");
});
});
String format = sb.toString();
这应该是您想要的格式。 您还可以像这样链接附加方法:
sb.append("\t").append(section.getSectionName()).append("\n");
您的代码的问题在于它
- 仅在 lambda 之间使用字符串数据,在其外部无法看到
- 您可以在“循环”的每一步中覆盖它
关于java - 如何将java层的数据组装成一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42367448/