0

I have a ArrayList of CustomObject, my object is simply made of two values x and y

MyObject = (double)x && (double)y 

What I want to do is:

  1. remove duplicate from array : simply remove duplicate object and if the objects have the same x keep the one if the higher y.
  2. reorder the list depending on the x value (x is for the time, y is a factor)

I have tried using Collections.sort to reorder my array and using a set to remove duplicate but nothing works.

Collections.sort(listPoints, new Comparator<MyObject>(){
    @Override
    public int compare(MyObject lhs, MyObject rhs) {
        return Double.compare(lhs.y, rhs.y);  
    }
});

Collections.sort(listPoints, new Comparator< MyObject >(){
    @Override
    public int compare(MyObject lhs, MyObject rhs) {
        return Double.compare(lhs.x, rhs.x);  
    }
});
DavidPostill
  • 7,734
  • 9
  • 41
  • 60
user2335528
  • 161
  • 1
  • 3
  • 13

4 Answers4

2

Sorting a list twice with different comparators will not work. You need to compare both x and y in the same comparator.

public int compare(MyObject lhs, MyObject rhs) {
    int result = Double.compare(lhs.y, rhs.y);
    if (result != 0) return result;
    return Double.compare(lhs.x, rhs.x);
}

Using a set to remove duplicates will work if MyObject correctly implements the equals() and hashCode() methods.

yole
  • 92,896
  • 20
  • 260
  • 197
0

For getting unique elements for your custom class you can just add all elements to something like HashSet. For using this you need to override the Object#hashCode() method to let it return the same hashCode() value x and y of MyObject instance. Don't forget to override Object#equals() as well.

You can refer here for more on overriding hashCode() and equals().

Community
  • 1
  • 1
nitishagar
  • 9,038
  • 3
  • 28
  • 40
0

You can implement Comparable<MyObject> in MyObject class and then use TreeSet<MyObject>, as result you have sorted unique values.

Tkachuk_Evgen
  • 1,334
  • 11
  • 17
0

To remove duplicates and keep the sorted order, i would suggest the following:

  • You store the Objects of type MyObject in a List
  • Sort them as you are doing with x field
  • iterate over the list and check for duplicates with previous elements (implements equals and hashCode methods in MyObject class) and remove one with less value in 'y' field.
SMA
  • 36,381
  • 8
  • 49
  • 73