Java Stream How to - Reduce String array to a single String value








Question

We would like to know how to reduce String array to a single String value.

Answer

//w  w  w .j a va 2  s. c  o  m
import java.util.function.BinaryOperator;
import java.util.stream.Stream;

public class Main {

  public static void main(String[] args) {
    BinaryOperator<String> adder = (a, b) -> {
      return a + b;
    };
    String[] alphabets = { "Just", " Java 8"," HTML" };
    String sum = Stream.of(alphabets).reduce(" ", adder);

    System.out.println("Alphabets:" + sum);
  }

}

The code above generates the following result.