gpt4 book ai didi

java - 如何计算ArrayList中某个单词出现的次数?

转载 作者:行者123 更新时间:2023-12-02 03:25:03 25 4
gpt4 key购买 nike

我编写了以下代码并得到了输出。导入java.util.ArrayList;

public class DuplicatesinArrayList {

public static void main(String[] args) {

ArrayList <String> al = new ArrayList<>();
al.add("Soumen");
al.add("Rahul");
al.add("Soumen");
al.add("Ram");
al.add("Rahul");
al.add("Rahul");
al.add("Rahul");
al.add("Ram");
al.add("Ram");
al.add("Ram");
al.add("Ram");

for (int i = 0; i < al.size(); i++) {
int ctr = 0;
for (int j = 0; j < al.size(); j++) {
if(al.get(i).equals(al.get(j)))
ctr++;
}
System.out.println(al.get(i)+" present " + ctr + " times");
}
}
}

结果如下:

Soumen present 2 times
Rahul present 4 times
Soumen present 2 times
Ram present 5 times
Rahul present 4 times
Rahul present 4 times
Rahul present 4 times
Ram present 5 times
Ram present 5 times
Ram present 5 times
Ram present 5 times

我希望每个单词都有一个结果。有人可以帮忙吗?

最佳答案

您可以使用 map

Map<String, Integer> map = new HashMap<>();
for (String s : al) {
if (map.containsKey(s)) map.put(s, map.get(s) + 1);
else map.put(s, 1);
}

for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey()+" present " + entry.getValue() + " times");
}

或者您可以使用 java8 流:

al.stream().collect(groupingBy(o -> o, counting())).forEach((name, count) -> System.out.println(name + " present " + count + " times"));

关于java - 如何计算ArrayList中某个单词出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39057561/

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