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

时间:2017-01-04 09:08:19

标签: java arraylist count

以下是代码片段,我想找到多次出现的动物名称。

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

        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;

1 个答案:

答案 0 :(得分:4)

最简单的解决方案,恕我直言将流动动物列表,按名称和计数分组:

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