从集合中查找重复项的最快方法是什么

时间:2014-02-14 07:10:05

标签: java collections

这就是我尝试过的,不知怎的,我觉得这不对,或者这不是性能最佳的应用程序,所以有更好的方法来搜索和从Map中获取重复值或作为事实上任何收藏。并且可以更好地遍历集合。

public class SearchDuplicates{
    public static void main(String[] args) {
        Map<Integer, String> directory=new HashMap<Integer, String>();
        Map<Integer, String> repeatedEntries=new HashMap<Integer, String>();

        // adding data
        directory.put(1,"john");
        directory.put(2,"michael");
        directory.put(3,"mike");
        directory.put(4,"anna");
        directory.put(5,"julie");
        directory.put(6,"simon");
        directory.put(7,"tim");
        directory.put(8,"ashley");
        directory.put(9,"john");
        directory.put(10,"michael");
        directory.put(11,"mike");
        directory.put(12,"anna");
        directory.put(13,"julie");
        directory.put(14,"simon");
        directory.put(15,"tim");
        directory.put(16,"ashley");

        for(int i=1;i<=directory.size();i++) {
           String result=directory.get(i);
           for(int j=1;j<=directory.size();j++) {
              if(j!=i && result==directory.get(j) &&j<i) {
                 repeatedEntries.put(j, result);
              }
           }
           System.out.println(result);
        }
        for(Entry<Integer, String> entry : repeatedEntries.entrySet()) {
           System.out.println("repeated "+entry.getValue());   
        }
   }
}

任何帮助将不胜感激。提前致谢

4 个答案:

答案 0 :(得分:5)

您可以使用Set来确定条目是否重复。此外,repeatedEntries也可能是Set,因为密钥没有意义:

Map<Integer, String> directory=new HashMap<Integer, String>();
Set<String> repeatedEntries=new HashSet<String>();
Set<String> seen = new HashSet<String>();

// ... initialize directory, then:

for(int j=1;j<=directory.size();j++){
    String val = directory.get(j);
    if (!seen.add(val)) {
        // if add failed, then val was already seen
        repeatedEntries.add(val);
    }
}

以额外内存为代价,以线性时间(而不是当前算法的二次时间)完成工作。

编辑:这是一个循环的版本,它不依赖于从1开始的连续整数:

for (String val : directory.values()) {
    if (!seen.add(val)) {
        // if add failed, then val was already seen
        repeatedEntries.add(val);
    }
}

这将检测任何Map的重复值,无论密钥如何。

答案 1 :(得分:1)

您可以使用它来创建字数

    Map<String, Integer> repeatedEntries = new HashMap<String, Integer>();
    for (String w : directory.values()) {
        Integer n = repeatedEntries.get(w);
        n = (n == null) ? 1 : ++n;
        repeatedEntries.put(w, n);
    }

这将打印统计数据

    for (Entry<String, Integer> e : repeatedEntries.entrySet()) {
        System.out.println(e);
    }

答案 2 :(得分:1)

List,Vector有一个方法contains(Object o),它根据该对象是否存在于集合中而返回布尔值。

答案 3 :(得分:1)

您可以使用Collection.frequency使用

查找任何集合中的所有可能重复项
Collections.frequency(list, "a")

这是一个合适的example

找到最通用的方法

Set<String> uniqueSet = new HashSet<String>(list);
    for (String temp : uniqueSet) {
        System.out.println(temp + ": " + Collections.frequency(list, temp));
    }

上面的参考链接本身

相关问题