gpt4 book ai didi

java - 如何删除ArrayList中与原始元素重复的值

转载 作者:行者123 更新时间:2023-12-01 17:53:55 27 4
gpt4 key购买 nike

假设我有一个 ArrayList,其中包含要处理的特定文件的路径。但只有当文件夹中只有一个文件时,才能处理该文件。这就是我的意思:

我的数组列表

List<String> pathsToTheFile = new ArrayList<>();

C:\123\456\NameOfUniqueFolder0
C:\123\456\NameOfUniqueFolder1
C:\123\456\NameOfUniqueFolder2
C:\123\456\NameOfUniqueFolder3
C:\123\456\NameOfUniqueFolder4

假设我的第五个元素是

C:\123\456\NameOfUniqueFolder0

显然,它是我的 0 元素的重复,因为该文件夹内的文件根本不应该被处理。应从列表中删除 C:\123\456\NameOfUniqueFolder0。我不能在这里使用 SET ,因为它会“删除”重复项,但文件夹的一个路径仍然存在,并且里面的文件会被处理。

最佳答案

这里使用 HashMap 可能是有意义的。键可以是文件路径,如果键存在,则值将是文件出现的次数。像这样的事情:

Map<String, Integer> map = new HashMap<>();
map.put("C:\123\456\NameOfUniqueFolder0", 1);
map.put("C:\123\456\NameOfUniqueFolder1", 1);
map.put("C:\123\456\NameOfUniqueFolder2", 1);
map.put("C:\123\456\NameOfUniqueFolder3", 1);
map.put("C:\123\456\NameOfUniqueFolder4", 1);

现在,当出现新路径时,增加其计数器:

String newPath = "C:\123\456\NameOfUniqueFolder0";
Integer val = map.get(newPath);
map.put(newPath, val == null ? 1 : val.intValue() + 1);
}

最后,您可以迭代此映射,并检查每个键的计数器值。然后,您将只处理只出现过一次的文件:

for (Map.Entry<String, Integer> entry : map.entrySet()) {
int count = entry.getValue();
if (count == 1) {
// process this file
}
// otherwise skip this path
}

关于java - 如何删除ArrayList中与原始元素重复的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47089346/

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