我的第一篇文章&我只開始學習Java,所以請耐心等待。按值排序HashMap,它是一個具有多個變量的類的實例
我有一個HashMap,它存儲一個類的鍵和一個實例作爲對應的值(來自我稱爲Main
的類)。該對象有兩個變量。我想要做的是根據特定的對象變量獲得一個打印輸出,在這個例子中每年。這裏是我的代碼:
public class Main {
private String name;
private int year;
public Main(String name, int year) {
this.name = name;
this.year = year;
}
protected static Map<Integer, Main> input = new LinkedHashMap<Integer, Main>();
input.put(1, new Main("Chris", 1980);
input.put(2, new Main("Daphne", 1981);
input.put(3, new Main("Sandra", 1976);
input.put(4, new Main("Adele", 1980);
所以現在我想要做的是按年份列出每個人。所以,我的期望輸出應該是這樣的:
1976: Sandra
1980: Chris, Adele
1981: Daphne
非常感謝
做到這一點是使用流,例如
你需要寫一個排序功能。這:[堆棧溢出問題](http://stackoverflow.com/questions/780541/how-to-sort-a-hashmap-in-java)可能會有所幫助。 –
你有兩種選擇。使用for循環,或使用流。你將能夠找到很多例子,如果你谷歌「流hashmap組由」, –
感謝@NickZiebert,你能告訴我我將如何使用循環? –