-3

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.

soupap
  • 13
  • 3
  • You need to explain what the `List` should actually contain. What is the relationship between the input `T` and the output string? What have you tried? Where did it fail? – RealSkeptic Jun 17 '19 at 16:50
  • All Java objects have a `toString()` method. So for your `List`, just populate it with `t.toString()`. If you want the `List` to contain more useful information, you'll need to either override the `toString()` method, or provide your own method of determine how `T` should be represented as a `String` – Zephyr Jun 17 '19 at 16:50
  • Can you share a bit of code? – Tlaloc-ES Jun 17 '19 at 16:50
  • 2
    `static List toStringList(List al) {return al.stream().map(Object::toString).collect(Collectors.toList());}` – Elliott Frisch Jun 17 '19 at 16:51
  • 3
    And what doesn't work with the code you just added? – Zephyr Jun 17 '19 at 16:57

2 Answers2

1

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.

BugsForBreakfast
  • 712
  • 10
  • 30
-1

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

Yehonatan
  • 46
  • 5