仅提取Java中列表中的重复元素

时间:2014-02-22 05:51:53

标签: java list

Java列表包含重复的元素,如

[cat, apple, iphone, football, apple, adam, apple, football, cat, people, cat]
  • cat重复3次
  • football重复2次
  • apple重复3次

如何仅从列表中提取重复元素,以便最终列表具有 [cat, apple, football]

5 个答案:

答案 0 :(得分:2)

使用Set

List<String> findDuplicates(List<String> original) {
    Set<String> seen = new HashSet<String>();
    Set<String> seenTwice = new HashSet<String>();

    for (String s: original) {
        if (!seen.add(s)) {
            seenTwice.add(s);
        }
    }
    return new ArrayList<String>(seenTwice);
}

答案 1 :(得分:1)

类似的东西:

String temp;
ArrayList<String> newStrings= new ArrayList<String>();
int x =0;
while(x < list.length){
 list.temp = get(x);
 for(int i =0; i < list.length; i++){
  if(temp.equals(list.get(i)) && i != x)
   newStrings.add(temp);



 }
x++
}

认为将从旧的

中将它们添加到新的arraylist中

答案 2 :(得分:1)

点击此处,评论中有一个可以解决问题的查找重复方法

How do I remove repeated elements from ArrayList?

答案 3 :(得分:0)

idea(s):使用从单词映射到出现的映射Map<String, Integer>

答案 4 :(得分:0)

另一个想法:

1. Create a set to store repeating items.
2. Create a set to store already seen items.
3. Begin loop to iterate around the array/list you have.
  3.1. If the current item is found in the already seen items set add it to repeating items set.
  3.2. Add the current item to already seen items set.
4. End loop.