简体   繁体   中英

Using ListIterator to remove duplicates

/** Return a list of all items in L that appear more than once.
*  Each item appears once in the result.
*/
static List<String> duplicates(List<String> L) {
    ArrayList<String> result = new ArrayList<String>();
    int n;
    n = 0;
    for (ListIterator<String> p1 = L.listIterator(); p1.hasNext();
         n += 1) {
        String x = p1.next();
        if (result.contains(x)) {
            continue;
        }
        int m;
        m = L.size() - 1;
        for (ListIterator<String> p2 = L.listIterator(L.size());
             m > n; m -= 1) {
            if (x.equals(p2.previous())) {
                result.add(x);
                break;
            }
        }
    }
    Collections.sort(result);
    return result;
}

I am trying to revise this code so that I don't use any other variables other than result, p1, and p2. This is what I have for now, but I am pretty lost on how to work this out.

    ListIterator<String> p1 = L.listIterator();
    while (p1.hasNext()) {
        String x = p1.next();
        if result.contains(x)) {
            continue;
        }

Since you have to remove duplicates, is there any reason you using ArrayList ?

This can solve your issue in one line;

Set<String> result = new TreeSet<String>(p1);

Also, to simplify your code, would recommend to use for-each loop rather than the iterator .

for(String s : p1)
{ // do some operation with the String you got here.  }

这也可以满足您的需求:

List<String> noDuplicates = new ArrayList<String>(new TreeSet<String>(initialList));

This is very complex. You would do yourself a favour by using the for(String s: List<String>) construct. You may also want to use a Set to help you find duplicates. Here's what a solution might look like.

Set<String> items = new HashSet<>();
Set<String> dupes = new TreeSet<>();
for(String s: L) {
  if (!items.add(s)) {
    // collect your duplicate here
    dupes.add(s);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM