基于另一个类中可用的参数对List进行排序

我有一些Java Comparator接口的设计问题。

我有一个类,其中包含一组简单的自定义数据结构:

 class data { Long ID; int Priority; ... } 

ID是唯一的,因此可以使用ID‍‍‍‍‍获取整个数据。

和容器类:

 class Container { Set mySet = ...; List myList = ...; ... } 

出于某些不可避免的原因,我需要并行保存排序的data ID List 。 我需要按Priority排序List

因为, Comparator应该比较Priority它应该实现Comparator 。 但List仅包含ID ,并且Priority不能直接使用。

这就是问题。 List只有ID 。 因此,Comparator类无法访问Priority

我该如何设计这样的概念?

你可以使用闻起来更高阶函数的东西。 也就是说,创建一个静态函数,它将从Long到int(这是优先级)或数据的排序映射,并返回一个新的Comparator。

类Foo有一个静态方法getComparator ,它接受一个Orange。 Orange是一个具有getPriority方法的类,它使ID返回相应的优先级。 getComparator方法构造一个新的Comparator对象。 新的Comparator对象的compare方法有两个ID。 它查找两个ID的相应优先级并进行比较。

 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); }; } } 

我的java有点生疏,所以代码可能有缺陷。 但总体思路应该有效。

用法:

 // 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)); 

我还没有举例说明Orange的外观。

我假设您在某处存储了List ..在Comparator中,您需要从数据类中调用getDataById方法,并对优先级进行排序。

检查下面的代码..我已经使用了一个类来实现多种目的..

理想情况下你会想把它分成更多的类 ..但这只是一个演示 ,如何实现你想要的……

 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(); } }