簡體   English   中英

如何計算arrayList中出現的相同值

[英]How to count the same value occurences in arrayList

這是我要查找動物名稱多次出現的代碼段。

我已經編寫了比較列表索引的代碼,但是無法理解如何比較名稱並計算每個名稱的出現次數。

        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;

恕我直言,最簡單的解決方案是流式動物列表,按名稱和數量分組:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM