Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find matching string occurrence in an ArrayList<String>

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.

like image 718
Marcus Avatar asked Aug 29 '26 00:08

Marcus


2 Answers

I may be missing something, but it looks like you could just do something simple like this, just keep the count of Dates in the HashMap, and iterate over the HashMap for the output:

    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, Integer> dateCount = new HashMap<String, Integer>();

    for (int i = 0; i < dates.size(); i++) {

        String date = dates.get(i);
        Integer count = dateCount.get(date);
        if (count == null){
          dateCount.put(date, 1);
        }
        else{
          dateCount.put(date, count + 1);
        }

    }
    for(String key : dateCount.keySet()){
        Integer occ = dateCount.get(key);
        System.out.println(key + ", " + occ);
    }

Output:

1991-02-28, 2
1994-02-21, 1
like image 83
Daniel Nugent Avatar answered Aug 31 '26 12:08

Daniel Nugent


I haven't debugged your logic yet, but you can use Google Guava's index method to perform a groupBy.

like image 24
Amir Afghani Avatar answered Aug 31 '26 13:08

Amir Afghani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!