Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将java层中的数据组装成一个字符串_Java - Fatal编程技术网

如何将java层中的数据组装成一个字符串

如何将java层中的数据组装成一个字符串,java,Java,我有一个3层的java对象 该场景有几个部分: public class Scenario { private String scenarioId; private List<Section> sectionList; 在每个部分中,有几个标签: public class Section { private String sectionName; private List<String> labelList; 我想将3层数据组合成一个字符串,如: <Scen

我有一个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即可。但是你需要把它做成最终的,这样它就可以在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();
这应该是你想要的格式。 您还可以像这样链接append方法:

sb.append("\t").append(section.getSectionName()).append("\n");
代码的问题在于

只在lambda之间使用字符串数据,不能在lambda之外看到 在循环的每一步都覆盖它
这是另一种选择

scenario.getSectionList()
    .filter(section -> !section.getLabelList().isEmpty())
    .forEach(section -> {
        append(section.getSectionName(), section.getLabelList())
    });

private final void append(String section, List<String> labels){
   sb.append("\t").append(section).append("\n");

   labels.forEach(label -> {
       sb.append("\t\t").append(label).append("\n");
   });
}

您需要xml格式吗?这看起来像一个xml文件输出。我会帮助你的。