简体   繁体   中英

How do I convert from List<T> to List<String> in Java

In java I need to write a method which convert a list<T> to list<String> , I try this:

private List<String> convertTlistToString(List<T> listOfT) {
        List<String> convertList = new ArrayList<>();

        if (listOfT != null) {
            for (T list : listOfT) {
                String t = list.toString();
                convertList.add(t);
            }
        }

        return convertList;
    }

thank for your help.

As people mention in the comments, you can use Java .toString() method for each object on your List<T> and populate your List<String> .

You can also check out this and apply it to your case

How to Convert List<String> to List<Object>

You have many ways to solve it, I recommend you to post some code of your class and be more specific of what you wanna cast to String for populating your List<String> .

EDIT: The code you posted should work fine.

You should try List.toString(); It will convert it to String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM