سؤال

I have this map:

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

where EventiPerGiorno is a Comparable object. How can I get a sorted list from the map?

I tried with

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

But Comparable.sort() doesn't like the list as comparable. Is there a ComparableList?

EDIT

this is the comparable method...

public class EventiPerGiorno implements Comparable<EventiPerGiorno>{


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

}
هل كانت مفيدة؟

المحلول

Java Collections don't have any order associated with them. You could turn the Collection into a List first and then sort it.

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

For this, you will need to create some sort of List that implements Comparable. See How do I correctly implement Comparable for List in this instance? for an example.

Note that this is sorting the objects of type List<EventiPerGiorno>, not the objects of type EventiPerGiorno. If you are interested in sorting the latter, you might want this instead:

ArrayList<EventiPerGiorno> bigList = new ArrayList<EventiPerGiorno>();
for (List<EventiPerGiorno> list : mapEventi.values()) {
    bigList.addAll(list);
}
Collections.sort(bigList);

نصائح أخرى

You are attempting to sort a List of Lists. List doesn't implement Comparable. You'll have to create your own Comparator instance.

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

This will sort every list in your map:

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

Or if you perhaps want to retrieve a single sorted list without modifying the lists in the map:

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

You would need to extend List and make it implement Comparable. There is no default natural ordering that can be used to compare multiple Lists.

The collections framework wouldnt know if you wanted to sort the list by number of items, number of duplicates, or values within the list.

Then to sort you use:

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top