【问题标题】:How to remove all the occurences of a element if its duplicate in an arraylist [duplicate]如果元素在arraylist中重复,如何删除所有出现的元素[重复]
【发布时间】:2017-11-17 09:20:22
【问题描述】:

我有一个值列表 {"16","b","c","d","e","16","f","g","16","b"} ; 在这 16 和 b 重复,所以我想删除它们的所有条目,我需要输出为 c、d、e、f、g。下面的程序工作正常。有更好的解决方案吗?

public class Test {

 public static void main(String[] args) {

  ArrayList < String > l = new ArrayList < String > ();
  String[] str = {
   "16",
   "b",
   "c",
   "d",
   "e",
   "16",
   "f",
   "g",
   "16",
   "b"
  };


  for (String s: str) {
   l.add(s);
  }
  List ll = removeDups(l);
  l.removeAll(ll);
  System.out.println("Final List " + l);
 }

 private static List < String > removeDups(ArrayList < String > l) {
  List < String > ll = new ArrayList < String > ();
  for (String a: l) {
   int x = Collections.frequency(l, a);
   if (x > 1) {
    ll.add(a);
   }
  }
  return ll;
 }
}

【问题讨论】:

  • 在 Stackoverflow 上发布问题之前,请解释代码或对其进行评论。它对每个人都有帮助。
  • 事实上,removeDups 方法确实应该被称为findDups,因为它实际上并没有删除任何东西;它只是找到重复的项目。如果将l.removeAll(ll) 行移到removeDups 内部,那么 removeDups 实际上值得这个名字。
  • 考虑到 Collections.frequency 的顺序是O(n),你可以使用哈希映射做得更好。
  • 我投票结束这个问题,因为它属于codereview.stackexchange.com
  • @DawoodibnKareem:这个问题与stackoverflow.com/questions/203984/… 不重复。也不是解决方案。您提到的链接中建议的解决方案将为每个重复元素保留一个条目。但这里的问题是如果重复,则删除每个元素。它甚至不应该出现在列表中的once

标签: java arraylist duplicates core


【解决方案1】:

您可以使用 Set 从给定的数组列表中删除重复的元素。

这里是示例代码:

Set<String> myStrSet = new HashSet<String>();
Set<String> duplicateSet = new HashSet<String>();

         for(String str : myArrayList){
             if(myStrSet.contains(str)){
                  duplicateSet.add(str);
             } else {
                  myStrSet.add(str);
             }
         }

         for(String str : duplicateSet){
             myStrSet.remove(str);
         }

         for(String str : myStrSet){
             System.out.println("Print non-duplicate elements : " + str);
         }

【讨论】:

  • 我认为 OP 想要删除重复的数组元素的 all 实例;这会留下每个重复项的实例。
  • 是的,我想删除所有出现的事件,如果重复出现,不希望出现任何事件。
  • 我不知道这个答案是如何获得投票的,它有不止一个错字(myStrList 和 st)并且它没有删除重复项。
  • @Sammetanagasrinivas 我添加了新代码,这里第一个 for 循环会将重复元素添加到 duplicateSet 中,现在在第二个 for 循环中,我们将在 duplicateSet 的帮助下从 myStrSet 中删除元素,所以最后我们会得到一个没有重复元素的列表。
【解决方案2】:

您可以为每个元素比较indexlastIndex。如果它们是same,则元素是unique。我们可以过滤这些元素。

// imports
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// sample code
String[] str = {"16","b","c","d","e","16","f","g","16","b"};
List<String> list = Arrays.asList(str); // List from the array
List<String> newList = new ArrayList<String>();
for(String myStr : list){
    if(list.indexOf(myStr) == list.lastIndexOf(myStr)){
        /*
         * This is a unique element as its index and lastIndex in list are same.
         * Add it to new list.
         */
        newList.add(myStr);
    }
}
// Freeing resources
str = null;
list = null;

System.out.println("Final List: "+ newList);

【讨论】:

  • 哇。它工作正常。非常感谢。
  • @Sammetanagasrinivas 你能投票赞成答案并接受答案作为解决方案吗?
【解决方案3】:

一种方法是使用流来查找每个元素的频率:

Map<String, Long> counts = yourList.stream()
    .collect(Collectors.groupingBy(
        Function.identity(),     // keep the element as the key
        Collectors.counting())); // values will be the count 

然后,您可以使用removeIf 根据条件删除元素,您将使用上面计算的频率图:

yourList.removeIf(elem -> counts.get(elem) > 1);

System.out.println(yourList); // [c, d, e, f, g]

另一种方法是首先找出哪些值有重复,哪些是唯一的。为此,我们可以使用Map&lt;String, Boolean&gt;

Map<String, Boolean> duplicates = new LinkedHashMap<>();
yourList.forEach(elem -> duplicates.compute(elem, (k, v) -> v != null));

在这里,我正在迭代列表,对于每个元素,我将其放入映射中,如果元素已经作为键存在,则将值计算为 true,如果它是唯一的,则计算为 false

然后,您可以在列表中使用removeIf,并带有一个简单地从映射中返回值的谓词:

yourList.removeIf(duplicates::get);

System.out.println(yourList); // [c, d, e, f, g]

【讨论】:

  • 我认为你的意思是低于仪式。这也可以正常工作。for(String s:l){ duplicates.put(s,(duplicates.containsKey(s)?true:false));} Iterator it= l.listIterator(); while(it.hasNext()){ String ss=(String)it.next(); if(duplicates.get(ss)){ it.remove(); } }
  • @Sammetanagasrinivas 是的,这似乎也有效。您不需要三元运算符。只要duplicates.put(s, duplicate.containsKey(s)); 就可以了。
【解决方案4】:

我觉得这样就可以了

public class DeleteDuplicates {

    public static void main(String[] args) {

        String[] str={"16","b","c","d","e","16","f","g","16","b"};
        List<String> l= new ArrayList<String>();
        Set<String> set = new HashSet<String>();

        for(String string : str) {

            if(set.add(string))
                l.add(string);
            else
                l.remove(string);
        }              

        System.out.println(l);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-10
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 2018-04-15
    相关资源
    最近更新 更多