Java Stream How to - Reduce the string list to a single string








Question

We would like to know how to reduce the string list to a single string.

Answer

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/*from w  w  w  . j a  v  a 2 s .  c o  m*/
public class Main {

  public static void main(final String[] args) {
    List<String> stringCollection = new ArrayList<>();
    stringCollection.add("ddd2");
    stringCollection.add("aaa2");
    stringCollection.add("bbb1");
    stringCollection.add("aaa1");
    stringCollection.add("bbb3");
    stringCollection.add("ccc");
    stringCollection.add("bbb2");
    stringCollection.add("ddd1");

    Optional<String> reduced =
            stringCollection
                    .stream()
                    .sorted()
                    .reduce((s1, s2) -> s1 + "#" + s2);
    reduced.ifPresent(System.out::println);

  }

}

The code above generates the following result.