Search code examples
javacollectionsfunctional-programmingfolding

How to implement a list fold in Java


I have a List and want to reduce it to a single value (functional programming term "fold", Ruby term inject), like

Arrays.asList("a", "b", "c") ... fold ... "a,b,c"

As I am infected with functional programming ideas (Scala), I am looking for an easier/shorter way to code it than

sb = new StringBuilder
for ... {
  append ...
}
sb.toString

Solution

  • What you are looking for is a string join() method which Java has since 8.0. Try one of the methods below.

    1. Static method String#join(delimiter, elements):

      Collection<String> source = Arrays.asList("a", "b", "c");
      String result = String.join(",", source);
      
    2. Stream interface supports a fold operation very similar to Scala’s foldLeft function. Take a look at the following concatenating Collector:

      Collection<String> source = Arrays.asList("a", "b", "c");
      String result = source.stream().collect(Collectors.joining(","));
      

      You may want to statically import Collectors.joining to make your code clearer.

      By the way this collector can be applied to collections of any particular objects:

      Collection<Integer> numbers = Arrays.asList(1, 2, 3);
      String result = numbers.stream()
              .map(Object::toString)
              .collect(Collectors.joining(","));