【问题标题】:JAVA HashMap duplicatesJAVA HashMap 重复
【发布时间】:2014-12-17 22:59:06
【问题描述】:

我正在尝试在目录中查找文件的重复项。

我对这个块有问题,它以文件地址作为参数:

public void findFiles(ArrayList<File> list){
    HashMap<String, File> hmap = new HashMap<String, File>();
    hmap.put(list.get(0).getName(), list.get(0));
    //System.out.println(hmap);

    for(Entry<String, File> entry : hmap.entrySet()){
        String key = entry.getKey();
        File value = entry.getValue();
// i don't understand what I need to write below 
        if (hmap.containsKey(key))
        {
            System.out.println("Duplicate: " + key + " in "+ value.getAbsolutePath());
        }
    }
}    

我应该如何重写我的 if 语句?

System.out.println(hmap);  

还有下一个例子:

    {File 2.txt=D:\Folder1\Folder1-2\Folder1-2-1\File 2.txt}
    {DFolder1.txt=D:\Folder1\Folder1-2\Folder1-3-1\DFolder1.txt}
    {File 1.txt=D:\Folder1\Folder1-2\File 1.txt}
    {File 1.txt=D:\Folder1\Folder1-3\File 1.txt, File 3.txt=D:\Folder1\Folder1-3\File 3.txt}
    {File 3.txt=D:\Folder1\File 3.txt}        

我有两个“文件 1.txt”

【问题讨论】:

标签: java arrays if-statement hashmap duplicates


【解决方案1】:

您只将列表的第一个元素添加到地图中,然后遍历地图。但我认为您的代码不需要映射,您可以使用 HashSet。大纲:

  1. 创建一个 HashSet。
  2. 遍历文件列表
  3. 检查文件是否已经在集合中(如果 set.contains(...)),如果为真,则您找到了重复文件。 else: 将文件添加到集合中。

【讨论】:

    【解决方案2】:

    当您遍历条目时,您的地图不会有重复的键。这就是地图的定义方式。将文件添加到地图时必须检查重复项。

    if (hmap.containsKey(key)) 将始终返回 true,因为您刚刚从地图中获得了该密钥。

    您必须遍历列表中的文件:

    public void findFiles(ArrayList<File> list){
        HashMap<String, File> hmap = new HashMap<String, File>();
        for (File file : list) {
            if (hmap.containsKey(file.getName()) {
                System.out.println("Duplicate: " + file.getName() + " in "+ hmap.get(file.getName()).getAbsolutePath());
            } else {          
                hmap.put(file.getName(), file);
            }
        }
    } 
    

    【讨论】:

      【解决方案3】:

      不要使用地图来查找重复项。使用一套。这个想法是遍历每个文件,检查它是否已经在集合中,如果不是,则将其添加到集合中。

      public List<File> findDuplicates(List<File> files) {
          Set<File> filesChecked = new HashSet<>();
          List<File> duplicates = new ArrayList<>();
      
          for (File f : files) {
              if (filesChecked.contains(f)) {
                  duplicates.add(f);
              } else {
                  filesChecked.add(f);
              }
          }
      
          return duplicates;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-30
        • 2013-03-04
        • 2018-01-02
        • 2011-12-24
        • 1970-01-01
        • 2015-02-05
        • 2021-10-15
        • 2012-03-20
        相关资源
        最近更新 更多