-2

Note: This question is for my assignment. So there are some rules which might seem to be not normal.

I just realized my question before doesn't make sense. So I edited it.

Assume that I have a list containing integers [1,2,3,4,1,2,1,5]

By using an iterator, how can I remove duplicated items while keeping the order of items undisrupted?

The expected result for above list should be [1,2,3,4,5] And contain() method is not allowed to use.

What I currently came up with is the same as what Manash Ranjan Dakua answered in this question How do I remove repeated elements from ArrayList?

public static void main(String[] args){
ArrayList<Object> al = new ArrayList<Object>();
al.add("abc");
al.add('a');
al.add('b');
al.add('a');
al.add("abc");
al.add(10.3);
al.add('c');
al.add(10);
al.add("abc");
al.add(10);
System.out.println("Before Duplicate Remove:"+al);
for(int i=0;i<al.size();i++){
    for(int j=i+1;j<al.size();j++){
        if(al.get(i).equals(al.get(j))){
            al.remove(j);
            j--;
        }
    }
}
System.out.println("After Removing duplicate:"+al);

}

But if I wish to use Iterator instead of for loops here? How can I achieve that(remove duplicated items while keeping order unchanged)?

If the question is not clear enough or too vague. Pls point out! I'll try to rephrase it.

Thanks for help!

Eric Chen
  • 49
  • 5

2 Answers2

4

You don't need to use Iterator to achieve that. A simple way is using LinkedHashSet which allows to contain unique elements only like HashSet (No Duplicates) and maintains insertion order.

Example:

List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,1,2,1,5));
Set<Integer> set = new LinkedHashSet<>();
set.addAll(list);
// or as suggested by assylias, Set<Integer> set = new LinkedHashSet<>(list);
System.out.println(list);
System.out.println(set);

Output:

[1, 2, 3, 4, 1, 2, 1, 5]
[1, 2, 3, 4, 5]
Yahya
  • 13,349
  • 6
  • 30
  • 42
0

You can simply call .next() again which will allow you to move on to the next element in the array. However if you want to get a new iterator for the rest of the elements, it would be best for you to use .next() through the rest of the list you have, adding each element to a new data structure and then call .iterator() on that new data structure.

Ryan G.
  • 1
  • 2