TreeMap 遍历
public class Eee {
public static void main(String[] args) {
TreeMap treeMap = new TreeMap<>();
treeMap.put("s", 2);
treeMap.put("w", 3);
treeMap.put("d", 1);
treeMap.put("f", 0);
treeMap.put("h", 9);
treeMap.put("q", 11);
treeMap.put("a", 25);
//遍历1
System.out.println("======================遍历一========================");
Iterator it1 = treeMap.keySet().iterator();
while(it1.hasNext()){
String key = it1.next();
Integer value = treeMap.get(key);
System.out.println("key=" + key + " ; " + "value=" + value);
}
//遍历二
System.out.println("======================遍历二========================");
Iterator> it2 = treeMap.entrySet().iterator();
while(it2.hasNext()) {
Entry entry = it2.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("key=" + key + " ; " + "value=" + value);
}
}
}
======================遍历一========================
key=a ; value=25
key=d ; value=1
key=f ; value=0
key=h ; value=9
key=q ; value=11
key=s ; value=2
key=w ; value=3
======================遍历二========================
key=a ; value=25
key=d ; value=1
key=f ; value=0
key=h ; value=9
key=q ; value=11
key=s ; value=2
key=w ; value=3
TreeMap 根据key排序
同下
TreeMap 根据value排序
public class Eee {
public static void main(String[] args) {
TreeMap treeMap = new TreeMap<>();
treeMap.put("s", 2);
treeMap.put("w", 3);
treeMap.put("d", 1);
treeMap.put("f", 0);
treeMap.put("h", 9);
treeMap.put("q", 11);
treeMap.put("a", 11);
//treeMap在put()的时候底层会compareTo根据key升序排列
System.out.println("treeMap = " + treeMap);
// 根据value排序一
List> entryArrayList1 = new ArrayList<>(treeMap.entrySet());
Collections.sort(entryArrayList1, Comparator.comparing(Map.Entry::getValue));
System.out.println("entryArrayList1=" + entryArrayList1);
// 根据value排序二
List> entryArrayList2 = new ArrayList<>(treeMap.entrySet());
Collections.sort(entryArrayList2, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));
System.out.println("entryArrayList2=" + entryArrayList2);
// 根据value排序三
List> entryArrayList3 = new ArrayList<>(treeMap.entrySet());
Collections.sort(entryArrayList3, new Comparator>() {
@Override
public int compare(Map.Entry o1, Map.Entry o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
System.out.println("entryArrayList3=" + entryArrayList3);
//treeMap中的排序依然没变,变得只是装treeMap的Arraylist
System.out.println("treeMap = " + treeMap);
}
}
treeMap = {a=11, d=1, f=0, h=9, q=11, s=2, w=3}
entryArrayList1=[f=0, d=1, s=2, w=3, h=9, a=11, q=11]
entryArrayList2=[f=0, d=1, s=2, w=3, h=9, a=11, q=11]
entryArrayList3=[f=0, d=1, s=2, w=3, h=9, a=11, q=11]
treeMap = {a=11, d=1, f=0, h=9, q=11, s=2, w=3}