gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:39:25 25 4
gpt4 key购买 nike

这是我想要找到多次出现的动物名称的代码片段。

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

        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()));

关于java - 如何计算arrayList中相同值的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41459946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com