sort a List based on a parameter available in another class

后端 未结 2 1638
名媛妹妹
名媛妹妹 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 08:48

    You could use something that smells like higher order functions. That is, make a static function that takes a map of sorts from Long to int (which is the priority) or data and returns a new Comparator.

    The class Foo has a static method getComparator which takes an Orange. An Orange is a class that has a method getPriority which takes an ID an return the corresponding priority. The getComparator method constructs a new Comparator object. The new Comparator object's compare method takes two IDs. It looks up the corresponding priorities of the two IDs and compares them.

    public interface Orange {
        // Looks up id and returns the corresponding Priority.
        public int getPriority(Long id);
    }
    
    public class Foo {
        public static Comparator getComparator(final Orange orange) {
            return new Comparator() {
                public int compare(Long id1, Long id2) {
                    // Get priority through orange, or
                    // Make orange juice from our orange.
                    // You may want to compare them in a different way.
                    return orange.getPriority(id1) - orange.getPriority(id2);
            };
        }
    }
    

    My java is a bit rusty so the code may be flawed. The general idea should work, though.

    Usage:

    // This is defined somewhere. It could be a local variable or an instance
    // field or whatever. There's no exception (except is has to be in scope).
    Collection c = ...;
    ...
    Orange orange = new Orange() {
        public int getPriority(Long id) {
            // Insert code that searches c.mySet for an instance of data
            // with the desired ID and return its Priority
        }
    };
    Collections.sort(c.myList, Foo.getComparator(orange));
    

    I have not given an example on how an Orange could look.

提交回复
热议问题