0

I have a file which I convert it into List<List<String>>

After doing this, I do some processing and then I need the file (which is now a List of List) to be converted into a string.

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

Output : When I append List , 2 \n\n are appended. I need to remove those and have only 1 \n. how can I do that?

vsminkov
  • 10,912
  • 2
  • 38
  • 50
Tiya
  • 553
  • 8
  • 26
  • 1
    `modifiedString.replace("\n\n", "\n");` should be `modifiedString=modifiedString.replace("\n\n", "\n");`. Possible duplicate (although I didn't test if that is main, or only problem so I will not vote) http://stackoverflow.com/questions/12734721/string-not-replacing-characters – Pshemo Sep 14 '16 at 19:58
  • Could replace: `tempList.add(convertListToString(listOfString));` with: `tempList.addAll(listOfString);`. ie: flatten the list then convert to string in one step. This would avoid the double `\n` unless you have empty strings. – ebyrob Sep 14 '16 at 20:01
  • Thank You all. I am on Java 6 because my project asks me to. I tried tempList.addAll(listOfString); as suggested by ebyrob and it worked. – Tiya Sep 14 '16 at 20:48
  • What debugging have you done? Can you narrow it down to a small handful of lines? https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Joe C Sep 14 '16 at 21:42

1 Answers1

0

Java 8 gives you a pretty elegant way of doing this with streams.

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());
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • 1
    Or `doc.stream().flatMap(List::stream).forEach(sb::append);`. Or `System.out.println(doc.stream().flatMap(List::stream).collect(joining("\n")));`. – shmosel Sep 14 '16 at 20:14