当前位置: 首页 > 知识库问答 >
问题:

如何在Java中从ArrayList中删除dulpicates?

束志业
2023-03-14
Set<Object> valueSet = new HashSet<Object>();
        for(HashMap<String, Object> map: mDataList){
                valueSet.addAll(map.values());
        }

但是我们不能在集合中存储HashMap。我想要HashMap与键,值对作为返回值,这将被添加到列表中。也就是说,最终的值应该采用ArrayList>格式。

你能在这方面帮助我吗?谢了。

共有1个答案

姬翰林
2023-03-14

Set应该能够包含一个HashMap。

我假设这里的重复表示键,值对在2个HashMap之间是相同的。在这种情况下,您可以尝试

Set<HashMap<String, Object>> abc = new HashSet<HashMap<String, Object>>();
HashMap<String, Object> a1 = new HashMap<String, Object>();
a1.put("a", "a");

HashMap<String, Object> a2 = new HashMap<String, Object>();
a2.put("a", "a");

HashMap<String, Object> a3 = new HashMap<String, Object>();
a3.put("c", "c");

abc.add(a1);
abc.add(a2);
abc.add(a3);

for (HashMap<String, Object> each : abc){
    System.out.println(each.toString()); //{a=a}, {c=c}
}

根据您的评论编辑

String yourkey = "key";
List<HashMap<String, Object>> oldList = new ArrayList<HashMap<String, Object>>();

HashMap<String, Object> a1 = new HashMap<String, Object>();
a1.put(yourkey, "1");

HashMap<String, Object> a2 = new HashMap<String, Object>();
a2.put(yourkey, "1");

HashMap<String, Object> a3 = new HashMap<String, Object>();
a3.put(yourkey, "2");

oldList.add(a1);
oldList.add(a2);
oldList.add(a3);

HashMap<Object, Object> newMap = new HashMap<Object, Object>();
for (HashMap<String, Object> each : oldList){
    // Put the value as key. Duplicate will be overridden
    newMap.put( each.get(yourkey), each);
}

List<HashMap<String, Object>> noDuplicateList = new ArrayList<HashMap<String, Object>>();
for (Object each : newMap.keySet()) {
    noDuplicateList.add( (HashMap)newMap.get(each) );
}

System.out.println(noDuplicateList); // [{key=2}, {key=1}]
 类似资料:
  • 我有一个程序,它从文件中获取输入,将文件中的每个单词保存为令牌,然后将每个令牌添加到数组列表中。 问题是arrayList出现了例如[“cat”,“dog”,“”,“”,“bird”],我不想在arrayList中出现空格。 总之,我的代码如下: 应该会删除空格,我已经通过从非文件数组列表中删除空格进行了测试。奇怪的是,如果我将其更改为,它将从ArrayList中删除cat。

  • 这段代码运行良好,但我想知道它的性能,我指的是它的总体时间复杂度?

  • 问题内容: 我有一个包含一些对象的对象,例如,每个对象都有一个and 属性。如何从其中仅删除具有特定“名称” 的对象? 问题答案: 您可以使用如下形式:

  • 我有一个arraylist,它包含一对整数(例如int i,int j)。但它可能包含重复对(如(int i,int j)和(int j,int i))。现在如何在O(n)时间复杂度中去除重复。

  • 我想要一个数组列表,并限制元素删除。我该怎么做?

  • 问题内容: 我有一个具有静态对象ArrayList的ClassA 现在,我要像这样从此列表中删除一个对象 这是用Meteorit类编写的。但是,当我想使用ArrayList中的对象时,它将引发异常。 我使用Iterator从ArrayList中删除对象,但是现在我不知道如何在这种情况下使用它。 问题答案: 这是因为某个线程实际上正在for每个循环中查看此列表,也许您正在尝试在for-each主体中