gpt4 book ai didi

java - 删除重复元素并计算 ArrayList 中的重复次数

转载 作者:行者123 更新时间:2023-11-30 06:21:59 26 4
gpt4 key购买 nike

这比我想象的要困难。我有一个排序的字符串(单词)数组列表,我的任务是删除重复项并打印出每个单词的列表,然后是该单词的重复次数。我只想说它比我预期的要复杂。在尝试了不同的事情之后,我决定使用 HashMap 来存储单词(键)、值(重复)。

这是代码。 Dictionary是排序后的ArrayList,Repetitions是HashMap。

public void countElements ()
{
String word=dictionary.get(0);
int wordCount=1;
int count=dictionary.size();
for (int i=0;i<count;i++)
{
word=dictionary.get(i);

for (int j=i+1; j<count;j++)
{


if(word.equals(dictionary.get(j)))
{

wordCount=wordCount+1;
repetitions.put(word, wordCount);
dictionary.remove(j--);
count--;

}


}
}

出于某种我不明白的原因(我是初学者),在我调用dictionary.remove(j--)方法后,变量j减1,即使它应该是i+1。我缺少什么?任何有关如何正确执行此操作的想法将不胜感激。我知道最好使用迭代器,但这可能会变得更加困惑。非常感谢。

最佳答案

使用流的版本:

    final Map<String, Long> countMap = dictionary.stream().collect(
Collectors.groupingBy(word -> word, LinkedHashMap::new, Collectors.counting()));
System.out.println("Counts follow");
System.out.println(countMap);
System.out.println("Duplicate-free list follows");
System.out.println(countMap.keySet());

在这里,我们使用每个元素(即每个单词)作为结果映射中的键对列表的元素进行分组(使用 Collectors.groupingBy),并计算该单词的出现次数(使用 Collectors.counting()).

外部收集器 (groupingBy) 使用 counting 收集器作为下游收集器,收集(此处为计数)单个单词的所有出现次数。

我们在这里使用 LinkedHashMap 来构建映射,因为它维护了添加到其中的键值对的顺序,因为我们希望保持单词在初始列表中的顺序相同.

还有一件事:countMap.keySet() 不是 List。如果你想最终得到一个List,只需new ArrayList(countMap.keySet())即可。

关于java - 删除重复元素并计算 ArrayList 中的重复次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47945702/

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