遍歷丶排序TreeMap的值
阿新 • • 發佈:2018-12-10
今天給大家說說怎麼把TreeMap 的值進行排序,TreeMap 預設排序規則:按照key的字典順序來排序(升序)
而HashMap在放入的時候已經內部規定好排序了,TreeMap可以可以自定義排序,廢話不多說,上程式碼!
首先,這裡建立了一個User類如下:
public class User {
private String name;
private int age;
private int id;
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", id=" + id + "]";
}
public User(String name, int age, int id) {
super();
this.name = name;
this.age = age;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this .name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
然後呢,根據鍵排序,建立測試類如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
Map<Integer, User> map = new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
map.put(5, new User("張三", 12, 3));
map.put(6, new User("李四", 14, 4));
map.put(2, new User("王五", 10, 9));
map.put(9, new User("趙六", 19, 1));
map.put(3, new User("宋琦", 22, 7));
map.put(6, new User("關羽", 8, 6));
// 根據鍵來排序
Iterator<Entry<Integer, User>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
System.out.print(iter.next().getKey() + "\t");
}
下來就是根據值排序了,我們先根據年齡排序:
List<Map.Entry<Integer, User>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, User>>() {
@Override
public int compare(Entry<Integer, User> o1, Entry<Integer, User> o2) {
return o1.getValue().getAge() - o2.getValue().getAge();
}
});
for (Entry<Integer, User> entry : list) {
System.out.print(entry.getValue().getAge() + "\t");
}
再下來我們根據id排序:
List<Map.Entry<Integer, User>> list2 = new ArrayList<Map.Entry<Integer, User>>(map.entrySet());
Collections.sort(list2, new Comparator<Map.Entry<Integer, User>>() {
@Override
public int compare(Entry<Integer, User> o1, Entry<Integer, User> o2) {
return o1.getValue().getId() - o2.getValue().getId();
}
});
for (Entry<Integer, User> entry : list2) {
System.out.print(entry.getValue().getId() + "\t");
}
**我們在排序值得時候,是把TreeMap放到List裡進行排序,所以,取出來的時候也是必須要從list裡取**
好了.今天的分享就到這裡,如果發現錯誤請及時聯絡更改,以免誤人子弟!