有 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层数据组合成一个字符串,如:

<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;

共 (2) 个答案

  1. # 1 楼答案

    我想可能有一些代码丢失了,但是我假设您有所有的getter和setter,并且希望字符串像您的示例中那样构建在lambda中。您只需使用StringBuilderStringBuffer即可。但是您需要使它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();
    

    这应该是你想要的格式。 您还可以像这样链接append方法:

    sb.append("\t").append(section.getSectionName()).append("\n");
    

    代码的问题在于

    1. 只在lambda之间使用字符串数据,不能在lambda之外看到
    2. 在“循环”的每一步都覆盖它
  2. # 2 楼答案

    这是另一种选择

    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");
       });
    }