Java Convert Object List To String List

Java Convert Object List To String List | Here we will discuss how to convert a list of objects to a list of strings in Java. An object can hold any value because the java.lang.Object class is a superclass for all Java classes.

Let us see an example to convert an object list to a string list where the object list contains a list of primitive or string values. For this, we will take a list of strings, and iterate each element in the object list. Each element will be converted to the string using the String.valueOf() method. The valueOf() method of the string class is used to convert primitive or object values to the string type.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {

        List<Object> objects = new ArrayList<>();
        objects.add("Hello");
        objects.add(9);
        objects.add(40.99);
        objects.add(true);

        // convert object list to String list
        List<String> listString = new ArrayList<>();
        for (Object object : objects) {
            listString.add(String.valueOf(object));
        }

        // display list
        System.out.println("List: " + listString);
    }
}

Output:-

List: [Hello, 9, 40.99, true]

When it comes to the Student, Employee, or similar class type of object then the definition of the toString() method plays an important role while converting. Let us see a program for it.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Object> objects = new ArrayList<>();
        objects.add(new Student(101, "William"));
        objects.add(new Student(102, "Amelia"));
        objects.add(new Student(103, "Oliver"));

        // convert object list to String list
        List<String> listString = new ArrayList<>();
        for (Object object : objects) {
            listString.add(String.valueOf(object));
        }

        // display list
        System.out.println("List: " + listString);
    }
}

class Student {
    private int id;
    private String name;

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }
}

Output:-

List: [Student [id=101, name=William], Student [id=102, name=Amelia], Student [id=103, name=Oliver]]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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