首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何计算arrayList中相同值的出现次数

问如何计算arrayList中相同值的出现次数
EN

Stack Overflow用户
提问于 2017-01-04 17:08:19
回答 0查看 76关注 0票数 1

下面是我想要查找多次出现的动物名称的代码片段。

我已经编写了比较列表索引的代码,但无法理解如何比较名称和计算每个名称出现的次数。

代码语言:javascript
复制
        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;
EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41459946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档