Sorting a vector using comparator

Posted on 2006-04-10
Last Modified: 2008-02-01
I have a vector of objects.  Each object contains status, from, and to.  I'm guessing I'd need to use comparator but uncertain as to how to implement it so that it will sort on any of the three criteria.

Thanks for your help
Question by:tbboyett
    LVL 2

    Expert Comment

    You can sort by two ways: you provide Comparator, or your objects are implementing Comparable.
    In firt variant you can sort objects from any type as long as Comparator you provide is accurate(I used string sort of string representation). In second variant you can only sort objects that "knows about each other". That's why I removed strings and numbers. I think example is self talking. For more info read javadoc of Collections.sort().

    import java.util.Vector;
    import java.util.Comparator;
    import java.util.Collections;

    public class Dummy
        public static void main(String[] args)

            //WAY 1, with Comparator
            Vector v = new Vector();
            v.add(new Integer(1));
            v.add(new Object(){ public String toString(){return "unknown";}});
            Collections.sort(v,new CompareStatusesCustom());
            System.out.println("sorted:" + v);

            //Way 2, each object must implement comparable,
            //Strings and numbers objects have compareTo method
            // so we only have to make our custom object to be comparable
            Vector v2 = new Vector();
            v2.add(new MyObject("completed"));
            v2.add(new MyObject("started"));
            v2.add(new MyObject("unknown"));
            System.out.println("sorted2:" + v2);

        public static class CompareStatusesCustom implements Comparator {
            public int compare(Object o1, Object o2)

        public static class MyObject extends Object implements Comparable
            private String value;

            public MyObject(String value)
                this.value = value;

            public String toString(){return value;}

            public int compareTo(Object o)
    LVL 86

    Accepted Solution

    Use a custom Comparator with a means of changing the sort field. This one sets it using the ctor, but you should also supply a setter method so you can reuse the same instance.

    Collections.sort(datas, new Sorter(Sorter.SortOn.TO));


                static class Sorter implements Comparator {
                      public enum SortOn {
                            STATUS, FROM, TO;
                      private SortOn sortOn;
                      public Sorter(SortOn sortOn) {
                            this.sortOn = sortOn;
                      public int compare(Object o1, Object o2) {
                            Data d1 = (Data)o1;
                            Data d2 = (Data)o2;
                            switch(sortOn) {
                                  case STATUS:
                                        return d1.getStatus().compareTo(d2.getStatus());
                                  case FROM:
                                        return d1.getFrom().compareTo(d2.getFrom());
                                  case TO:
                                        return d1.getFrom().compareTo(d2.getFrom());
                                        return Integer.MIN_VALUE;
    LVL 86

    Expert Comment


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
    Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
    The viewer will learn how to implement Singleton Design Pattern in Java.
    Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now