Search code examples
javajava-8java-stream

can I convert List of String into single String using java 8 streams


I have written a below code using java.

List<String> list = new ArrayList<String>();
list.add("book1");
list.add("book2");
list.add("book3");
list.add("book4");


String combined = "";

for(int i=0;i<list.size();i++) {
    combined = combined + (i+1)+ ". "+list.get(i)+" \r\n";
}

System.out.println(combined);

OUTPUT

1. book1 
2. book2 
3. book3 
4. book4 

How can I write this code using streams. I tried doing below:

String combined2 = "";

List<String> list2 = IntStream.range(0, list.size()).mapToObj(i->i+1+". "+list.get(i)+" \r\n").toList();


for(String s:list2) {
    combined2 = combined2+s;
}

System.out.println(combined2);

But I don't want to use for loop here. How can I improve my approach ?


Solution

  • You are almost there. You just need to use Stream.collect.

    Here is the modified code.

    String list2 = IntStream.range(0, list.size())
            .mapToObj(i-> i+1 + ". " + list.get(i))
            .collect(Collectors.joining(System.lineSeparator()));
    

    output:

    1. book1
    2. book2
    3. book3
    4. book4