Med Desai
Med Desai

Reputation: 13

How to count the same value occurences in arrayList

Here is the snippet of code where I want to find the multiple occurrences of animal name.

I have written the code comparing the list indexes, but unable understand how to compare the names and count the number of occurrences of each name.

        List<Animals> animalList= new ArrayList<Animals>();

        try {
            CallableStatement stmt = conn.prepareCall(callProcedure, ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            boolean results = stmt.execute();

            if (results) {
                ResultSet rs = stmt.getResultSet();
                int count = 0;
                while (rs.next()) {

                    Animals animal = new Animals();

                    animal.setAnimalName(rs.getString("animal_name"));
                    animal.setAge(rs.getString("age"));
                    animal.setHealth(rs.getString("health"));
                    animalList.add(animal);
                    count++;             
                }
            }

            int nbOccurences = 1;

            for (int i = 0, length = animalList.size(); i < length; i++) {
                if (i < length - 1) {
                    if (animalList.get(i) == animalList.get(i+1)) {
                        nbOccurences++;
                    }
                } else {
                    System.out.println( animalList.get(i) + " occurs " + nbOccurences
                                    + " time(s)"); //end of array
                }

                if (i < length - 1 && animalList.get(i) != animalList.get(i+1)) {
                    System.out.println( animalList.get(i) + " occurs " + nbOccurences
                                    + " time(s)"); //moving to new element in array
                    nbOccurences = i;
                }

            }

        } catch (SQLException sqlE) {
            sqlE.printStackTrace();
        }

        return animalList;

Upvotes: 1

Views: 98

Answers (1)

Mureinik
Mureinik

Reputation: 311326

The easiest solution, IMHO would be to stream the animal list, group by the name and count:

Map<String, Long> nameCount = 
    animalList.stream()
              .collect(Collectors.groupingBy(Animal::getName, 
                                             Collectors.counting()));

Upvotes: 4

Related Questions