删除ArrayList问题中的重复项 [英] Remove duplicates from ArrayList issue
问题描述
yourList = new ArrayList< String>(new) LinkedHashSet<字符串>(yourList));
它可以工作,但由于ArrayList在HashMap中,所以我遇到了问题。 b
$ b
private void removeDuplicate(HashMap< String,ArrayList< LinkedList< String>>> p)
{
// (Map.Entry< String,ArrayList< LinkedList< String>> entry:p.entrySet())
{
ArrayList< LinkedList< String>的每个条目的循环;> partitions = entry.getValue();
partitions = new ArrayList< LinkedList< String>>(new LinkedHashSet< LinkedList< String>>(partitions));
问题在于, HashMap和以前完全一样!
变量分区不再有重复,但整个HashMap不变。
问题在哪里?
解决方案您只修改分区
这只是一个局部变量,你实际上并没有修改地图项的值,为了更新给定地图项的值,使用 Map.Entry#setValue(V value)
(Map.Entry< String,ArrayList< LinkedList< String>>>条目:p.entrySet(a) )){
ArrayList< LinkedList< String>> partitions = entry.getValue();
entry.setValue(new ArrayList<>(new LinkedHashSet<>(partitions)));
注意:这会移除 LinkedList
不重复字符串
重复项目
I'm trying to remove duplicates from ArrayLists with the popular technique:
yourList = new ArrayList<String>(new LinkedHashSet<String>(yourList));
It works, but since the ArrayList is in an HashMap I got the problem.
private void removeDuplicate(HashMap<String, ArrayList<LinkedList<String>>> p)
{
//cycle for each entry of HashMap
for(Map.Entry<String, ArrayList<LinkedList<String>>> entry : p.entrySet())
{
ArrayList<LinkedList<String>> partitions = entry.getValue();
partitions = new ArrayList<LinkedList<String>>(new LinkedHashSet<LinkedList<String>>(partitions));
}
}
The problem is after that, the HashMap is exactly the same like before! The variable partitions has no duplicates anymore, but the entire HashMap is unchanged. Where is the problem?
You only modify partitions
which is only a local variable, you don't actually modify the value of the map entry, to update the value of a given map entry use Map.Entry#setValue(V value)
for(Map.Entry<String, ArrayList<LinkedList<String>>> entry : p.entrySet()) {
ArrayList<LinkedList<String>> partitions = entry.getValue();
entry.setValue(new ArrayList<>(new LinkedHashSet<>(partitions)));
}
NB: This will remove LinkedList
duplicates not String
duplicates
这篇关于删除ArrayList问题中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!