0

I have a java object with 3 layers.

the scenario has several sections:

public class Scenario {

private String scenarioId;
private List<Section> sectionList;

within each section, there are several labels:

public class Section {

private String sectionName;
private List<String> labelList;

I want to assemble the 3 layer data into one string, like:

<Scenario>
  <section1>
     <label11 data>
     <label12 data>
  <section2>
     <label21 data>
     <label22 data>
  ...

I have the code as following to pick each layers' parameter, but how to assemble it into one string:

            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;
QSY
  • 127
  • 1
  • 8

2 Answers2

1

I guess there is some code missing or anything, but I assume you have all getters and setters and you want the String to be built in a lambda like in your example. You simply need to work with a StringBuilder or StringBuffer. But you to make it final so that it can be used in a 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();

That should be the format you want. You can also chain the append method like this:

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

The Problem with your code is that it

  1. Just uses the String data in between the lambda and cannot be seen outside of it
  2. You overwrite it in every step of the "loop"
Pascal Schneider
  • 405
  • 1
  • 5
  • 19
0

Here is another alternative.

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");
   });
}
Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62