简体   繁体   中英

How do I return an ordered list given a HashMap?

I have a HashMap of objects called Cards. The key is the Card, while the value is an integer which represents how many of a card is in the "deck". Each turn, I need to return an ordered list based on how many cards are left. How do I go about doing this? Here is my code so far:

import java.util.Collections;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Field {
    public Field() {
        Map<Card,Integer> backingMap = new HashMap<Card,Integer>();
    }
    public void buyCardFromField(Card c) {
        if(backingMap.get(c) != 0) {
            backingMap.put(c,backingMag.get(c) - 1);
        }
        else {
            throw new RunTimeException("This card is no longer available!");
        }
    }
    public List getCardsInZone() {
        List<Card> cardList = new ArrayList();
        for(Card element: backingMap.keySet()) {
            cardList.add(element);
        //Some method to sort the arrayList? I'm not sure what to do here?//
        }
        return cardList;
    }
}

You can create a comparator class for your Card class and then call Collections.sort(arraylist).

Java documentation

The easiest way is probably to get the entries from the hashmap and sort it. The benefit of using the entry set is that your card object doesn't have need to have a count attribute.

Set<Entry<Card, Integer>> entries = backingMap.entrySet(); 
ArrayList<Entry<Card, Integer> entryList = new ArrayList();
entryList.addAll(entries);
Lists.sort(entryList, myNewComparator);
return entryList;

Of course you need a comparator that sorts Entries in descending order based on the the value attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM