I have an ArrayList<String> containing dates represented as Strings with the format yyyy-MM-dd, e.g:
ArrayList<String> dates = new ArrayList<>();
dates.add("1991-02-28");
dates.add("1991-02-28");
dates.add("1994-02-21");
I'd like to know the number of times the same String (date) appears in the list. In the example above, I'd like to achieve the following output:
1991-02-28, 2
1994-02-21, 1
I've tried the following code
ArrayList<String> dates = new ArrayList<>();
dates.add("1991-02-28");
dates.add("1991-02-28");
dates.add("1994-02-21");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
HashMap<String, String> dateCount = new HashMap<String, String>();
String first = dates.get(0);
int count = 1;
dateCount.put(first, String.valueOf(count));
for (int i = 1; i < dates.size(); i++) {
if (first.equals(dates.get(i))) {
count++;
} else {
first = dates.get(i);
dateCount.put(dates.get(i), String.valueOf(count));
count = 0;
}
}
for (String date : dates) {
String occ = dateCount.get(date);
System.out.println(date + ", " + occ);
}
But it prints
1991-02-28, 1
1991-02-28, 1
1994-02-21, 2
I'm tired, stuck, and turning to SO as a last resort. Any help is appreciated.
1991-02-28, 2and1994-02-21, 1@AmirAfghani