0

The first method finds the duplicate and the second removes it. I tried the following code and it does not work. I don't understand why. to be done using two methods. When I call the methods, they do not remove the duplicates. The arraylist is unchanged. I want to remove the duplicates using two methods.

public static int find(ArrayList<String> s, int i) {

    for (int j = i + 1; j < s.size(); j = j + 1) {
        if (s.get(i) == s.get(j)) {
            return j;
        }
    }

    return -1;
}


public static void removeDuplicates(ArrayList<String> s) {
    for (int i = 0; i < s.size(); i = i + 1) {
        int foundAt = (find(s, i));
        if (foundAt >= 0) {
            s.remove(i);
        }
    }
}
george
  • 13
  • 5

5 Answers5

1

Don't be bothered:

public static List<String> removeDups(final List<String> orig)
{
    return new ArrayList<>(new LinkedHashSet<>(orig));
}

(note the use of LinkedHashSet, we want to preserve element iteration ordering)

fge
  • 119,121
  • 33
  • 254
  • 329
0

Why don't you simply dump it in a Set

List<String> listduplicates =  new ArrayList<String>(10);
//add elements to the list
Set<String> as = new HashSet<String>(listduplicates );

List<String> listunique =  new ArrayList<String>(as.size());

listunique now give unique elements

Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35
0

If you want to do it with two methods, and following your same idea, you could fix your methods to be:

   public static int find(List<String> s, int j) {
        for(int i=j;i<s.size();i++) {
            if (s.lastIndexOf(s.get(i)) != i)  {
                return i;
            }
        }
        return -1;
    }


    public static void removeDuplicates(ArrayList<String> s) {
        for (int j=0; j<s.size();j++) {
            int i = -1;
            while((i=find(s,j))>=0) {
                s.remove(i);
            }
        }
    }
Raul Guiu
  • 2,374
  • 22
  • 37
0

If you are using Java 8 you can use the Stream API with the distinct() operation to eleminate duplicates:

List<Integer> list = Arrays.asList(5, 3, 6, 5, 4, 6);
List<Integer> filtered = list.stream().distinct().collect(Collectors.toList());
System.out.println("filtered: " + filtered); // [5, 3, 6, 4]
micha
  • 47,774
  • 16
  • 73
  • 80
0

I have checked your code and it runs fine and removes duplictaes from the list. You may change removeDuplicates method to remove duplicates that come later in the list.

 public static void removeDuplicates(ArrayList<String> s) {
            for (int i = 0; i < s.size(); i = i + 1) {
                int foundAt = (find(s, i));
                if (foundAt >= 0) {
                    s.remove(foundAt);
                }
            }
        }
Rishav Basu
  • 391
  • 4
  • 12