Java订购一个集合

时间:2013-11-06 14:10:31

标签: java comparable

我有这张地图:

Map<Integer,List<EventiPerGiorno>> mapEventi=new HashMap<Integer,List<EventiPerGiorno>>();

其中 EventiPerGiorno 可比较对象。 如何从地图中获取排序列表?

我试过

Collection<List<EventiPerGiorno>> collection=mapEventi.values()
Comparable.sort(collection);

但是Comparable.sort()不喜欢列表可比。有ComparableList吗?

修改

这是可比的方法......

public class EventiPerGiorno implements Comparable<EventiPerGiorno>{


    @Override
    public int compareTo(EventiPerGiorno o) {
        return this.getPrimoSpettacolo().compareTo(o.getPrimoSpettacolo());
    }

}

4 个答案:

答案 0 :(得分:1)

Java Collections没有与之关联的任何订单。您可以先将Collection转换为List,然后对其进行排序。

Collection<List<EventiPerGiorno>> collection = mapEventi.values()
YourComparableList<List<EventiPerGiorno>> list = new YourComparableList(collection);
Collections.sort(list);

为此,您需要创建一些实现List的{​​{1}}。有关示例,请参阅How do I correctly implement Comparable for List in this instance?

请注意,这是对Comparable类型的对象进行排序,而不是List<EventiPerGiorno>类型的对象。如果您有兴趣对后者进行排序,您可能需要这样做:

EventiPerGiorno

答案 1 :(得分:1)

您正在尝试对列表列表进行排序。 List没有实现Comparable。您必须创建自己的Comparator实例。

    Map<String, List<EventiPerGiorno>> map = new HashMap<String, List<EventiPerGiorno>>();

    List<List<EventiPerGiorno>> lists = new ArrayList(map.values());

    Collections.sort(lists, new Comparator<List<EventiPerGiorno>>() {
        @Override
        public int compare(List<EventiPerGiorno> o1, List<EventiPerGiorno> o2) {
            // ??? This is up to you.
            return 0;
        }
    });

答案 2 :(得分:1)

这将对地图中的每个列表进行排序:

for (List<EventiPerGiorno> list : mapEventi.values()) {
    Collections.sort(list);
}

或者,如果您可能想要检索单个排序列表而不修改地图中的列表:

int someKey = ...;
List<EventiPerGiorno> list = new ArrayList<>(mapEventi.get(someKey));
Collections.sort(list);
return list;

答案 3 :(得分:0)

您需要扩展List并使其实现Comparable。没有可用于比较多个列表的默认自然顺序。

集合框架无法知道您是否要按项目数,重复项数或列表中的值对列表进行排序。

然后排序你使用:

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List%29