How to use Comparator in Java to sort

后端 未结 14 1798
时光取名叫无心
时光取名叫无心 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:46

    The solution can be optimized in following way: Firstly, use a private inner class as the scope for the fields is to be the enclosing class TestPeople so as the implementation of class People won't get exposed to outer world. This can be understood in terms of creating an APIthat expects a sorted list of people Secondly, using the Lamba expression(java 8) which reduces the code, hence development effort

    Hence code would be as below:

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    
    public class TestPeople {
        public static void main(String[] args) {
            ArrayList peps = new ArrayList<>();// Be specific, to avoid
                                                        // classCast Exception
    
            TestPeople test = new TestPeople();
    
            peps.add(test.new People(123, "M", 14.25));
            peps.add(test.new People(234, "M", 6.21));
            peps.add(test.new People(362, "F", 9.23));
            peps.add(test.new People(111, "M", 65.99));
            peps.add(test.new People(535, "F", 9.23));
    
            /*
             * Collections.sort(peps);
             * 
             * for (int i = 0; i < peps.size(); i++){
             * System.out.println(peps.get(i)); }
             */
    
            // The above code can be replaced by followin:
    
            peps.sort((People p1, People p2) -> p1.getid() - p2.getid());
    
            peps.forEach((p) -> System.out.println(" " + p.toString()));
    
        }
    
        private class People {
            private int id;
    
            @Override
            public String toString() {
                return "People [id=" + id + ", info=" + info + ", price=" + price + "]";
            }
    
            private String info;
            private double price;
    
            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;
            }
        }
    }
    

提交回复
热议问题