一、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);
}
}
标签:Map,name,子类,treeMap,TreeMap,Dog2,public
From: https://www.cnblogs.com/ndmtzwdx/p/18470906