How to use Comparator in Java to sort

后端 未结 14 1797
时光取名叫无心
时光取名叫无心 2020-11-22 02:19

I learned how to use the comparable but I\'m having difficulty with the Comparator. I am having a error in my code:

Exception in thread \"main\" java.lang.C         


        
相关标签:
14条回答
  • 2020-11-22 02:59

    Here's an example of a Comparator that will work for any zero arg method that returns a Comparable. Does something like this exist in a jdk or library?

    import java.lang.reflect.Method;
    import java.util.Comparator;
    
    public class NamedMethodComparator implements Comparator<Object> {
    
        //
        // instance variables
        //
    
        private String methodName;
    
        private boolean isAsc;
    
        //
        // constructor
        //
    
        public NamedMethodComparator(String methodName, boolean isAsc) {
            this.methodName = methodName;
            this.isAsc = isAsc;
        }
    
        /**
         * Method to compare two objects using the method named in the constructor.
         */
        @Override
        public int compare(Object obj1, Object obj2) {
            Comparable comp1 = getValue(obj1, methodName);
            Comparable comp2 = getValue(obj2, methodName);
            if (isAsc) {
                return comp1.compareTo(comp2);
            } else {
                return comp2.compareTo(comp1);
            }
        }
    
        //
        // implementation
        //
    
        private Comparable getValue(Object obj, String methodName) {
            Method method = getMethod(obj, methodName);
            Comparable comp = getValue(obj, method);
            return comp;
        }
    
        private Method getMethod(Object obj, String methodName) {
            try {
                Class[] signature = {};
                Method method = obj.getClass().getMethod(methodName, signature);
                return method;
            } catch (Exception exp) {
                throw new RuntimeException(exp);
            }
        }
    
        private Comparable getValue(Object obj, Method method) {
            Object[] args = {};
            try {
                Object rtn = method.invoke(obj, args);
                Comparable comp = (Comparable) rtn;
                return comp;
            } catch (Exception exp) {
                throw new RuntimeException(exp);
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 02:59
    public static Comparator<JobSet> JobEndTimeComparator = new Comparator<JobSet>() {
                public int compare(JobSet j1, JobSet j2) {
                    int cost1 = j1.cost;
                    int cost2 = j2.cost;
                    return cost1-cost2;
                }
            };
    
    0 讨论(0)
  • 2020-11-22 03:04

    Two corrections:

    1. You have to make an ArrayList of People objects:

      ArrayList<People> preps = new ArrayList<People>(); 
      
    2. After adding the objects to the preps, use:

      Collections.sort(preps, new CompareId());
      

    Also, add a CompareId class as:

    class CompareId implements Comparator {  
        public int compare(Object obj1, Object obj2) {  
            People t1 = (People)obj1;  
            People t2 = (People)obj2;  
    
            if (t1.marks > t2.marks)  
                return 1;   
            else  
                return -1;
        }  
    }
    
    0 讨论(0)
  • 2020-11-22 03:06

    You should use the overloaded sort(peps, new People()) method

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    
    public class Test 
    {
        public static void main(String[] args) 
        {
            List<People> peps = new ArrayList<>();
    
            peps.add(new People(123, "M", 14.25));
            peps.add(new People(234, "M", 6.21));
            peps.add(new People(362, "F", 9.23));
            peps.add(new People(111, "M", 65.99));
            peps.add(new People(535, "F", 9.23));
    
            Collections.sort(peps, new People().new ComparatorId());
    
            for (int i = 0; i < peps.size(); i++)
            {
                System.out.println(peps.get(i));
            }
        }
    }
    
    class People
    {
           private int id;
           private String info;
           private double price;
    
           public People()
           {
    
           }
    
           public People(int newid, String newinfo, double newprice) {
               setid(newid);
               setinfo(newinfo);
               setprice(newprice);
           }
    
           public int getid() {
               return id;
           }
    
           public void setid(int id) {
               this.id = id;
           }
    
           public String getinfo() {
               return info;
           }
    
           public void setinfo(String info) {
               this.info = info;
           }
    
           public double getprice() {
               return price;
           }
    
           public void setprice(double price) {
               this.price = price;
           }
    
           class ComparatorId implements Comparator<People>
           {
    
            @Override
            public int compare(People obj1, People obj2) {
                   Integer p1 = obj1.getid();
                   Integer p2 = obj2.getid();
    
                   if (p1 > p2) {
                       return 1;
                   } else if (p1 < p2){
                       return -1;
                   } else {
                       return 0;
                   }
                }
           }
        }
    
    0 讨论(0)
  • 2020-11-22 03:08

    Do not waste time implementing Sorting Algorithm by your own. Instead; use

    Collections.sort() to sort data.

    0 讨论(0)
  • 2020-11-22 03:09

    For the sake of completeness.

    Using Java8

    people.sort(Comparator.comparingInt(People::getId));
    

    if you want in descending order

    people.sort(Comparator.comparingInt(People::getId).reversed());
    
    0 讨论(0)
提交回复
热议问题