一、TreeMap
元素是一個鍵值對,可以去重並進行排序
1.先編寫一個Dog2類
public class Dog2{
private String name;
private int age;
public Dog2() {
}
public Dog2(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2.編寫一個測試類
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class TreeMapDemo1 {
public static void main(String[] args) {
//使用匿名內部類
TreeMap<Dog2, Integer> treeMap = new TreeMap<Dog2, Integer>(new Comparator<Dog2>() {
@Override
public int compare(Dog2 o1, Dog2 o2) {
//按年齡來排序,如果年齡相同,則比較姓名是否相同
int i=o1.getAge()-o2.getAge();
return (i==0)?o1.getName().compareTo(o2.getName()):i;
}
});
Dog2 d1 = new Dog2("煤球",3);
Dog2 d2 = new Dog2("旺財",2);
Dog2 d3 = new Dog2("小灰",3);
Dog2 d4 = new Dog2("煤球",3);
Dog2 d5 = new Dog2("白線",4);
treeMap.put(d1,1);
treeMap.put(d2,2);
treeMap.put(d3,3);
treeMap.put(d4,4);
treeMap.put(d5,5);
//使用增強for迴圈來遍歷Map裡面的鍵
for(Dog2 i:treeMap.keySet()){
System.out.println(i);
}
//使用增強for迴圈來遍歷Map裡面的值
for(Integer i:treeMap.values()){
System.out.println(i);
}
//使用增強for迴圈來遍歷Map中的所有的鍵值對
//要想不報黃色警告可以指定Map.Entry的泛型
for(Map.Entry<Dog2,Integer> i:treeMap.entrySet()){
System.out.println(i);
}
System.out.println(treeMap);
}
}
二、TreeMap的練習題:(類似於TreeSet)
"aababcabcdabcde",獲取字串中每一個字母出現的次數要求結果:a(5)b(4)c(3)d(2)e(1)
import java.util.Map;
import java.util.TreeMap;
public class TreeMapTest1 {
public static void main(String[] args) {
TreeMap<Character, Integer> treeMap = new TreeMap<>();
String a="aababcabcdabcde";
char[] chars=a.toCharArray();
for (char aChar : chars) {
//判斷chars中的值在不在treeMap的鍵中,如果不在將該值新增到treeMap的鍵中,並將值賦為1
if (treeMap.containsKey(aChar)) {
treeMap.put(aChar, treeMap.get(aChar) + 1);
//如果在將其值加一
} else {
treeMap.put(aChar, 1);
}
}
System.out.println(treeMap);
StringBuffer s1 = new StringBuffer();
for(Map.Entry<Character,Integer> entry:treeMap.entrySet()){
Character b=entry.getKey();
Integer c=entry.getValue();
s1.append(b).append("(").append(c).append(")");
}
System.out.println(s1);
}
}