sort a List based on a parameter available in another class

后端 未结 2 1637
名媛妹妹
名媛妹妹 2021-01-23 08:29

I have some design problems with Java Comparator Interface.

I have a class which contains a Set of a simple custom data structure:



        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-23 09:00

    I assume that you have a List stored somewhere.. In Comparator, you need to invoke a getDataById method from your data class, and sort through Priority..

    Check the below code.. I have used a single class for many purpose..

    Ideally you would want to break it into more classes.. But this is just a Demo, how to achieve what you want..

    class Container {
        // List of Data  instances created..
        // This list has to be static, as it is for a class, 
        // and not `instance specific`
        public static List dataList = new ArrayList();
    
        // List of Ids, that you want to sort.
        private List idList = new ArrayList();
    
        // Populate both the list..
    
        // Have a method that will iterate through static list to 
        // find Data instance for a particular id
    
        public static Data getDataById(long id) {
            // Find Data with id from the list
    
            // Return Data
        }
    
        public void sortList() {
            Collections.sort(idList, new MyComparator());
        }
    }
    
    public MyComparator implements Comparator {
    
        public int compare(Long int1, Long int2) {
            Data data1 = Container.getDataById(int1);
            Data data2 = Container.getDataById(int2);
    
            return data1.getPriority() - data2.getPriority();
        }
    }
    

提交回复
热议问题