dazzle
dazzle

Reputation: 109

Can I convert List<Date> to ArrayList<String>?

I have a list of dates stored in List<Date> and get the data from method getDates. and now I want to convert it to ArrayList<String> but I got this error:

ArrayList cannot be applied to java.util.List.

because i want to change format of the date from List. And i have tried this one Convert ArrayList of String type into Date type? and to convert date, first date must stored as string but my case my date store in List. the problem is, i still cant to convert List to string.

This is my code:

List<Date> dates = getDates(date1, date2);
ArrayList<String> dateStringList = new ArrayList<>();
dateStringList.add(dates);

Is there a way to convert data in List<Date> to ArrayList<String>? I have tried so many ways but still got error.

Upvotes: 0

Views: 4485

Answers (2)

vss
vss

Reputation: 1153

You should use an enhanced for-loop to achieve it, like below:

List<Date> dates = getDates(date1, date2);
List<String> dateStringList = new ArrayList<>();

for (Date date : dates) {
    String dateStr = String.valueOf(date);
    dateStringList.add(dateStr);
}

In the above code, we actually loop each and every Date in the dates list, converting them to String, and adding them to the dateStringList list.

And if you need your dateString in a particular format, you should use the method below upon changing to the necessary format:

public static String dateToString(Date date) {
    String convertedDate = "";

    try {

        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        convertedDate = dateFormat.format(date);

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("dateToString_EX", e + "");
    }

    return convertedDate;
}

And call it like below inside the for() loop:

for (Date date : dates) {
    //String dateStr = String.valueOf(date);
    String dateStr = dateToString(date);
    dateStringList.add(dateStr);
}

Upvotes: 1

If you use the jack or JaCoCo (here more info about it) then you can use lambdas and streams on it!

List<Date> myVarList = Arrays.asList(new Date(), new Date(), new Date(), new Date());
List<String> myVarListString = new ArrayList<>();

myVarListString.addAll(myVarList.stream().map(x -> x.toString()).collect(Collectors.toList()));

System.out.println(myVarListString);
System.out.println(myVarList);

Upvotes: 0

Related Questions