2014-10-22 2 views
0

디렉토리에있는 파일의 중복을 찾으려고합니다.JAVA HashMap duplicate

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); 

그리고 다음 examlpes 있습니다

{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"

+0

가능한 중복 [HashMap의 중복을 허용?] (http://stackoverflow.com/questions/20537898/hashmap-allows-duplicates) – Xstian

+1

는이 디렉토리에 중복 파일을 만들 수 있습니까? – EvenPrime

답변

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); 
     } 
    } 
} 
2

는 당신은지도에 목록의 첫 번째 요소를 추가하고지도를 반복. 하지만 난 당신의 코드에 대한지도가 필요하지 않습니다 thinnk, 당신은 HashSet을 사용할 수 있습니다. 개요 :

  1. HashSet을 만듭니다.
  2. 파일 목록을 반복하십시오.
  3. 파일이 이미 세트에 들어 있는지 확인하십시오 (set.contains (...) 인 경우). 참이면 복제본을 볼 수 있습니다. else : 파일을 세트에 추가하십시오.
0

중복을 찾기 위해지도를 사용하지 마십시오. 세트를 사용하십시오. 아이디어는 모든 파일을 반복하고 이미 파일 세트에 있는지 확인한 다음 파일 세트에 추가합니다. 의

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; 
}