如何计算arraylist中出现的相同值

rpppsulh  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(288)

下面是我想查找多次出现的动物名称的代码片段。
我已经编写了比较列表索引的代码,但是无法理解如何比较名称和计算每个名称的出现次数。

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;
cnh2zyt3

cnh2zyt31#

最简单的解决方案是,输入动物列表,按名称和计数分组:

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

相关问题