Java Streams
Programming Techniques
Object Conversion
String Methods
Data Transformation

Using streams to convert a list of objects into a string obtained from the toString method

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In modern Java, the Stream API introduced in Java 8 provides a powerful set of tools for processing sequences of elements including collections like lists. One common task in Java programming is transforming a list of objects into a single string representation, often using the toString() method of the objects. This can be efficiently achieved using Java Streams, allowing for both readability and concise code.

Understanding Streams

A stream in Java can be understood as a sequence of elements supporting sequential and parallel aggregate operations. These operations are divided into intermediate (transformative) and terminal (finalizing) operations. Intermediate operations return a stream themselves, allowing for chaining, while terminal operations produce a result or a side-effect.

For instance, when you have a list of objects, and you need to transform this list into a string representation of each object, the Stream API can be used to map each object to its toString() representation and then collect these representations into a single string.

Practical Example

Consider a simple Java class, Person, with two fields, name and age:

java
1public class Person {
2    private String name;
3    private int age;
4
5    public Person(String name, int age) {
6        this.name = name;
7        this.age = age;
8    }
9
10    @Override
11    public String toString() {
12        return "Person{name='" + name + '\'' + ", age=" + age + '}';
13    }
14}

Now, suppose you have a List<Person> and you want to convert this list into a string where each Person object is represented by its toString() output:

java
1import java.util.Arrays;
2import java.util.List;
3import java.util.stream.Collectors;
4
5public class Example {
6    public static void main(String[] args) {
7        List<Person> people = Arrays.asList(
8            new Person("Alice", 30),
9            new Person("Bob", 25),
10            new Person("Charlie", 35)
11        );
12
13        String result = people.stream()
14                              .map(Person::toString)
15                              .collect(Collectors.joining(", "));
16
17        System.out.println(result);
18    }
19}

In this code:

  • people.stream() converts the list into a Stream<Person>.
  • .map(Person::toString) applies the toString() method of each Person object, transforming the stream into a Stream<String> containing the string representations.
  • .collect(Collectors.joining(", ")) is a terminal operation that concatenates all strings in the stream, adding a separator , between them.

The output will be:

 
Person{name='Alice', age=30}, Person{name='Bob', age=25}, Person{name='Charlie', age=35}

Advantages of Using Streams

Using streams in this way has several advantages:

  1. Code Clarity: High-level stream operations allow the code to express the "what" clearly without muddling it with the "how".
  2. Parallelizable: Under the hood, streams can be run in parallel with minimal changes to the code, taking advantage of multiple cores.
  3. Flexible: Stream operations are composable and reusable, enabling more complex operations to be built up from simpler ones.

Summary Table

FeatureDescription
StreamsEnable functional-style operations on collections
.map()Applies a function to each element of a stream
.collect()Performs mutable fold operations on data in the stream
Collectors.joining()Concatenates the input elements, separated by a defined delimiter

Conclusion

Stream API not only tidies the code but also makes it inherently more adaptable and parallelizable, which can be critical for performance in large-scale applications. The example and explanations provided demonstrate how streams can transform and manipulate data in collections seamlessly and effectively. Such methodologies encourage writing robust and efficient Java applications.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions