gpt4 book ai didi

JAVA HashMap 重复

转载 作者:行者123 更新时间:2023-12-01 18:25:00 27 4
gpt4 key购买 nike

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

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

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”

最佳答案

您仅将列表的第一个元素添加到映射中,然后迭代映射。但我认为你的代码不需要映射,你可以使用 HashSet。概要:

  1. 创建一个哈希集。
  2. 迭代文件列表
  3. 检查该文件是否已在集合中(如果 set.contains(...)),如果为 true 那么您发现了重复项。else: 将文件添加到集合中。

关于JAVA HashMap 重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26508380/

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