Anto Anto - 3 months ago 8
Java Question

converting elements of a list to string

I would like to obtain the string text of the elements stored in a list, say

List<Car>
. Would the toArray() and the toString() methods be the best options?

Answer

Yes, but doing it manually gives you more control:

// initialize with the exact length
List<String> stringsList = new ArrayList<String>(listOfCard.size()); 
for (Car car : listOfCars) {
    stringsList.add(car.toString());   
}

If you haven't overridden the toString() method and don't want to override id, you can use car.getName() isntead of car.toString() (or any property combination you like)