shantanu
shantanu

Reputation: 2008

Sorting points(in 2d,3d and so on) in java

What is the best way to sort the points(first based on x co-ordinate and if x is same then on y co-ordinate and if y is same then based on z co-ordinate and so on.) in java without implementing sorting algorithm?

In c++ it can be done very easily(as follows) with the help of pairs.

For 2D:

Vector < pair < int,int > > plane;
sort(plane.begin(),plane.end())

For 3D:

Vector < pair < int,pair < int,int > > > space;
sort(space.begin(),space.end());

Thanks in Advance. Shantanu

Upvotes: 0

Views: 532

Answers (2)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

There are few options in Java.

  1. Collections.sort(List l)

    Use java.lang.Comparable // For sorting only on the basis of one property

  2. Collections.sort(List l, Comparator c)

    Use java.util.Comparator // For sorting in more than one way

  3. If Uniqueness is needed, along with Sorting use TreeSet()

    TreeSet()   // Sorting in Natural order
    
    TreeSet(Comparator c)   // Sorting in more than one way.
    

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272657

You don't need to implement a sorting algorithm. You just need to implement a comparator, which can then be used with Collections.sort().

See Object Ordering from the Java Tutorial for more information.

Upvotes: 5

Related Questions