如果元素在arraylist中重复,如何删除元素的所有出现

时间:2017-06-15 03:29:51

标签: java arraylist duplicates core

我有一个包含值{“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;
 }
}

4 个答案:

答案 0 :(得分:2)

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

以下是示例代码:

def isempty(it):
    try:
        itcpy = itertools.tee(it,1)[0]
        itcpy.next()
        return False
    except StopIteration:
        return True

def empty_iterator():
    if False:
        yield

it = empty_iterator()
if not isempty(it):
    # won't print
    print(len(list(it)))

it = xrange(4)
if not isempty(it):
    # will print
    print(len(list(it)))

答案 1 :(得分:1)

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

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<String, Boolean>

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]

答案 2 :(得分:1)

您可以为每个元素比较 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);

答案 3 :(得分:0)

我认为这样做

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);
    }
}