Java 8 – Convert List of Objects to List of Strings

Introduction

Java 8 introduced the Stream API, which offers a powerful way to process collections of data. A common requirement is to convert a list of objects into a list of strings, often based on one or more fields of the objects. The Stream API, combined with lambda expressions and method references, makes this task straightforward and efficient.

In this guide, we’ll explore how to convert a list of objects to a list of strings using Java 8, covering various scenarios including custom objects, multiple fields, and custom formatting.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Example 1: Convert List of Objects Using a Single Field
    • Example 2: Convert List of Objects Using Multiple Fields
    • Example 3: Custom Formatting of Strings
    • Example 4: Handling Null Values in Object Fields
  • Conclusion

Problem Statement

You need to convert a list of objects into a list of strings, where each string represents an object based on one or more of its fields. This is useful in various scenarios, such as preparing data for display or logging.

Example:

  • Problem: Given a list of Person objects, convert it into a list of strings where each string is the person’s name.
  • Goal: Use Java 8’s Stream API to achieve this conversion in a clean and efficient manner.

Solution Steps

  1. Extract Field Values: Learn how to extract field values from each object in the list.
  2. Combine Multiple Fields: Explore how to combine multiple fields into a single string.
  3. Apply Custom Formatting: Implement custom formatting logic for the resulting strings.
  4. Handle Null Values: Ensure robustness by handling potential null values in object fields.

Java Program

Example 1: Convert List of Objects Using a Single Field

Let’s start with a simple example where we convert a list of Person objects to a list of strings containing only the names of the persons.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Java 8 - Convert List of Objects to List of Strings Using a Single Field
 * Author: https://www.rameshfadatare.com/
 */
public class ConvertListExample1 {

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Amit", 30),
            new Person("Priya", 25),
            new Person("Raj", 28)
        );

        // Convert list of Person objects to list of strings (names)
        List<String> names = people.stream()
                                   .map(Person::getName)
                                   .collect(Collectors.toList());

        System.out.println("Names: " + names);
    }
}

class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }
}

Output

Names: [Amit, Priya, Raj]

Explanation

  • map(Person::getName): Maps each Person object in the stream to its name field, resulting in a stream of strings (names).
  • collect(Collectors.toList()): Collects the stream of strings into a list.

Example 2: Convert List of Objects Using Multiple Fields

If you want to combine multiple fields into a single string, you can use lambda expressions to achieve this.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Java 8 - Convert List of Objects to List of Strings Using Multiple Fields
 * Author: https://www.rameshfadatare.com/
 */
public class ConvertListExample2 {

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Amit", 30),
            new Person("Priya", 25),
            new Person("Raj", 28)
        );

        // Convert list of Person objects to list of strings (name and age)
        List<String> personDetails = people.stream()
                                           .map(person -> person.getName() + " (" + person.getAge() + ")")
                                           .collect(Collectors.toList());

        System.out.println("Person Details: " + personDetails);
    }
}

class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Output

Person Details: [Amit (30), Priya (25), Raj (28)]

Explanation

  • map(person -> person.getName() + " (" + person.getAge() + ")"): Combines the name and age fields into a single string for each Person object.

Example 3: Custom Formatting of Strings

You can apply custom formatting to the strings by using formatted strings in the lambda expression.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Java 8 - Custom Formatting of Strings
 * Author: https://www.rameshfadatare.com/
 */
public class ConvertListExample3 {

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Amit", 30),
            new Person("Priya", 25),
            new Person("Raj", 28)
        );

        // Convert list of Person objects to list of formatted strings
        List<String> formattedDetails = people.stream()
                                              .map(person -> String.format("Name: %s, Age: %d", person.getName(), person.getAge()))
                                              .collect(Collectors.toList());

        System.out.println("Formatted Person Details: " + formattedDetails);
    }
}

class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Output

Formatted Person Details: [Name: Amit, Age: 30, Name: Priya, Age: 25, Name: Raj, Age: 28]

Explanation

  • String.format(): Provides a way to apply custom formatting to the output strings.

Example 4: Handling Null Values in Object Fields

It’s important to handle potential null values in object fields to avoid NullPointerException.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Java 8 - Handling Null Values in Object Fields
 * Author: https://www.rameshfadatare.com/
 */
public class ConvertListExample4 {

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Amit", 30),
            new Person(null, 25),
            new Person("Raj", 28)
        );

        // Convert list of Person objects to list of strings, handling null values
        List<String> personDetails = people.stream()
                                           .map(person -> {
                                               String name = person.getName() != null ? person.getName() : "Unknown";
                                               return String.format("Name: %s, Age: %d", name, person.getAge());
                                           })
                                           .collect(Collectors.toList());

        System.out.println("Person Details with Null Handling: " + personDetails);
    }
}

class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Output

Person Details with Null Handling: [Name: Amit, Age: 30, Name: Unknown, Age: 25, Name: Raj, Age: 28]

Explanation

  • Null Handling: The lambda expression includes a check for null values in the name field, providing a default value if necessary.

Conclusion

Converting a list of objects to a list of strings in Java 8 is straightforward using the Stream API. Whether you’re extracting a single field, combining multiple fields, applying custom formatting, or handling null values, the Stream API offers a clean and efficient way to achieve your goal. By leveraging these techniques, you can simplify your code and improve its readability and maintainability.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top