2017-02-21 52 views
0

我有一個3層的java對象。如何將數據從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> 
    ... 

我有代碼如下來挑選每個圖層的參數,但如何將它組裝成一個條G:

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

您是否需要xml格式? – user121290

+1

這看起來像一個XML文件輸出。 [這個答案](http://stackoverflow.com/questions/8865099/xml-file-generator-in-java)將幫助你。 – kantagara

回答

1

我想有一些代碼丟失或什麼,但我以爲你把所有getter和setter和你想的String你的例子建立在一個拉姆達等。您只需要使用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之間,不能被它
  2. 外面看
  3. 您可以在「循環」的每一步中覆蓋它
0

這是另一種選擇。

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"); 
    }); 
} 
相關問題