0

I am trying to remove all duplicate objects with the same value in one property.I have courses[] objects and they all contain a courseLevel that is composed of one four digit integer.

I am incrementing x from 0 in a loop and storing the data and reseting it every iteration of the loop to store new information in the next incremented courses[x] object.

        for (int n = 0; n < courses.length; n++) {
            if (courses[x].getCourseLevel() == courses[n].getCourseLevel()) {
                System.out.println("Duplicate" + courses[x]);
            }  
         }

As you can see I start with courses[x] and want to check if its courseLevel is equal to any of the other objects that have been created to that point but the problem is it checks its self,How can I check all courses[n] except courses[x]

Tried using equals() but couldn't compare int types.

OneU
  • 85
  • 6
  • 6
    You could try `&& x != n` – Compass Jan 05 '17 at 20:45
  • 2
    The simpler way would be to override the `equals()` and `hashCode()` methods and then put all the objects in a `Set` to get only the unique objects. – user2004685 Jan 05 '17 at 20:48
  • I actually tried that.I added all my objects to a list.Then to a set and back into the list.I then sorted them by the courseLevel(ascending).I still have dups though. – OneU Jan 05 '17 at 20:51
  • If you are using Java 8 then you can use approach from [here](http://stackoverflow.com/questions/27870136/java-lambda-stream-distinct-on-arbitrary-key). Just transform your array to stream: Arrays.stream(courses). – Dmitry Gorkovets Jan 05 '17 at 20:55

1 Answers1

0
for (int n = 0; n < courses.length; n++) {
        if ((courses[x].getCourseLevel() == courses[n].getCourseLevel()) && x != n) {
            System.out.println("Duplicate" + courses[x]);
        }  
     }
Trevor Bye
  • 686
  • 1
  • 6
  • 26