0

I have list of integer and I want create a for loop from sequence 1 to n skipping the elements which are already there in the List, So which is the best way or efficient way to do?

  • You can find a similar question here https://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist – Ravi Chandra May 30 '17 at 09:49
  • Possible duplicate of [How do I remove repeated elements from ArrayList?](https://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist) – Mohammad Hamedani May 30 '17 at 09:53
  • What does this question have to do with `hibernate` or `spring-mvc`? – Andreas May 30 '17 at 10:08

2 Answers2

1

Most efficient way, i.e. O(m+n), is to convert the List to a HashSet, then check using contains():

Set<Integer> set = new HashSet<>(list);
for (int i = 1; i <= n; i++) {
    if (! set.contains(i)) {
        // your code here
    }
}

If you don't convert to Set, and use the contains() method of List directly, performance would be O(mn), where m is number of elements in the list.

Andreas
  • 154,647
  • 11
  • 152
  • 247
-1

You can use hashset for the purpose it will automatically remove the repeated elements. So for your input array, put each element one by one in the hashset and at the end your hashset will contain the non repeated elements.

On doubts regarding hashshet refer: https://www.tutorialspoint.com/java/java_hashset_class.htm

pragadez
  • 89
  • 5
  • Question is not about removing duplicates from list. It's about a `for` loop, *skipping* values already in a list. – Andreas May 30 '17 at 10:09
  • To say exactly, you skip for only if there is a repeated value , which means there is a duplicate for a value. Internally Hashset uses contains method to check whether the input is present or not – pragadez May 30 '17 at 10:16
  • There is nothing in the question saying that the loop will modify the list. If list is `[2, 4, 5]` and `n = 7`, OP simply wants a loop that iterates the values `1`, `3`, `6`, and `7`. There are no "duplicates" in any of that. – Andreas May 30 '17 at 10:20