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);  
    }
});
1
  • What is a custom object? Commented Dec 24, 2014 at 9:24

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What do you mean by The sorting implemented by Collections.sort() is not stable?
Actually please disregard that. Collections.sort() does do a stable sort, but it's irrelevant here.
than you i'll give a try
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().

1 Comment

thai you i'll give a try
0

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.