How to Convert Stream to String in Java 8

Introduction

In Java 8, the Stream API allows you to efficiently process collections and sequences of elements. Sometimes, after processing a stream, you might want to convert it into a String, either by joining the elements with a delimiter or concatenating them directly. Java 8 provides several ways to achieve this using the Collectors.joining() method.

This guide will demonstrate how to convert a stream to a string in Java 8.

Solution Steps

  1. Create or Obtain a Stream: Generate or obtain a stream from a collection or another data source.
  2. Use Collectors.joining(): Convert the stream into a string by joining the elements with or without a delimiter.
  3. Display or Use the String: Print or use the resulting string.

Java Program

Example 1: Convert a Stream of Strings to a Single String (Without Delimiter)

import java.util.stream.Stream;
import java.util.stream.Collectors;

public class StreamToStringExample {
    public static void main(String[] args) {
        // Step 1: Create a stream of strings
        Stream<String> wordStream = Stream.of("Java", "is", "fun");

        // Step 2: Convert the stream to a string without a delimiter
        String result = wordStream.collect(Collectors.joining());

        // Step 3: Display the result
        System.out.println(result);  // Output: "Javaisfun"
    }
}

Output

Javaisfun

Explanation

  • Step 1: A stream of strings is created using Stream.of().
  • Step 2: The Collectors.joining() method is used to concatenate the elements without any delimiter.
  • Step 3: The resulting string is printed.

Example 2: Convert a Stream of Strings to a Single String (With a Space Delimiter)

import java.util.stream.Stream;
import java.util.stream.Collectors;

public class StreamToStringWithDelimiter {
    public static void main(String[] args) {
        // Step 1: Create a stream of strings
        Stream<String> wordStream = Stream.of("Java", "is", "fun");

        // Step 2: Convert the stream to a string with a space delimiter
        String result = wordStream.collect(Collectors.joining(" "));

        // Step 3: Display the result
        System.out.println(result);  // Output: "Java is fun"
    }
}

Output

Java is fun

Explanation

  • Step 1: A stream of strings is created using Stream.of().
  • Step 2: The Collectors.joining(" ") method is used to concatenate the elements with a space delimiter between them.
  • Step 3: The resulting string is printed.

Example 3: Convert a Stream of Integers to a String

import java.util.stream.Stream;
import java.util.stream.Collectors;

public class StreamOfIntegersToString {
    public static void main(String[] args) {
        // Step 1: Create a stream of integers
        Stream<Integer> numberStream = Stream.of(1, 2, 3, 4, 5);

        // Step 2: Convert the stream of integers to a string
        String result = numberStream.map(String::valueOf)
                                    .collect(Collectors.joining(", "));

        // Step 3: Display the result
        System.out.println(result);  // Output: "1, 2, 3, 4, 5"
    }
}

Output

1, 2, 3, 4, 5

Explanation

  • Step 1: A stream of integers is created using Stream.of().
  • Step 2: The integers are converted to strings using map(String::valueOf) and then concatenated using Collectors.joining(", ").
  • Step 3: The resulting string is printed.

Example 4: Convert a Stream of Custom Objects to a String

import java.util.stream.Stream;
import java.util.stream.Collectors;

public class StreamOfObjectsToString {
    public static void main(String[] args) {
        // Step 1: Create a stream of Employee objects
        Stream<Employee> employeeStream = Stream.of(
            new Employee("Ravi", 30),
            new Employee("Amit", 25),
            new Employee("Pooja", 35)
        );

        // Step 2: Convert the stream of Employee objects to a string
        String result = employeeStream.map(Employee::toString)
                                      .collect(Collectors.joining(", "));

        // Step 3: Display the result
        System.out.println(result);
    }
}

class Employee {
    private String name;
    private int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + ": " + age;
    }
}

Output

Ravi: 30, Amit: 25, Pooja: 35

Explanation

  • Step 1: A stream of Employee objects is created using Stream.of().
  • Step 2: Each Employee object is converted to a string using map(Employee::toString) and then concatenated using Collectors.joining(", ").
  • Step 3: The resulting string is printed.

Conclusion

In Java 8, converting a stream to a string is simple using the Collectors.joining() method. You can join the elements of the stream with or without a delimiter, and the process works for strings, numbers, or even custom objects. This approach is flexible and efficient for handling various data types.

Comments