2016-09-14 107 views
0

我有我把它轉換成List<List<String>>刪除空行

這樣做後一個文件,我做了一些處理,然後我需要的文件(也就是現在的List一個List)被轉換成字符串。

private static String convertListOfListToString(List<List<String>> listOfIncomingMsgListsTemp){ 
    List<String> tempList = new ArrayList<String>(); 
    for(List<String> listOfString : listOfIncomingMsgListsTemp){ 
     tempList.add(convertListToString(listOfString)); 
    } 
    String modifiedString = convertListToString(tempList); 
    modifiedString.replace("\n\n", "\n"); 
    System.out.println("modifiedString :\n" + modifiedString); 
    return modifiedString; 
} 

private static String convertListToString(List<String> list){ 
    StringBuilder sb = new StringBuilder(); 
    for (String s : list) 
    { 
     sb.append(s); 
     sb.append("\n"); 
    } 
    return(sb.toString()); 
} 

輸出: 當我追加列表,2 \ n \ n被追加。我需要刪除這些,只有1 \ n。 我該怎麼做?

+1

'modifiedString.replace( 「\ n \ n」, 「\ n」);'應'modifiedString = modifiedString.replace( 「\ n \ n」, 「\ n」);'。可能的重複(雖然我沒有測試,如果這是主要的,或者只有問題,所以我不會投票)http://stackoverflow.com/questions/12734721/string-not-replacing-characters – Pshemo

+0

可以替換:'tempList.add (convertListToString(listOfString));'with:'tempList.addAll(listOfString);'。即:展平列表,然後在一步中轉換爲字符串。除非你有空字符串,否則這將避免雙'\ n'。 – ebyrob

+0

謝謝大家。我在Java 6上,因爲我的項目要求我。我試過tempList.addAll(listOfString);正如ebyrob所建議的那樣,它起作用了。 – Tiya

回答

0

Java 8爲您提供了一種非常優雅的方式來處理流。

String[] text1 = { "hello", "java", "this", "is", "cool" }; 
String[] text2 = { "hello", "Mundo", "this", "is", "sparta" }; 
List<String> line = new ArrayList<>(); 
line.addAll(Arrays.asList(text1)); 
line.addAll(Arrays.asList(text2)); 

List<List<String>> doc = new ArrayList<>(); 
doc.add(line); 
doc.add(line); 
doc.add(line); 
StringBuilder sb = new StringBuilder(); 
doc.stream().forEach(a -> a.stream().forEach(x -> sb.append(x))); 

System.out.println(sb.toString()); 
+1

或'doc.stream()。flatMap(List :: stream).forEach(sb :: append);' 。或'System.out.println(doc.stream()。flatMap(List :: stream).collect(joining(「\ n」)));'。 – shmosel