import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<Student, String> tm=new TreeMap<Student, String>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num=o1.getName().compareTo(o2.getName());
int num2=num==0?o1.getAge()-o2.getAge():num;
return num2;
}
});
tm.put(new Student("李四", 38),"北京");
tm.put(new Student("赵六", 24),"上海");
tm.put(new Student("小强", 31),"沈阳");
tm.put(new Student("旺财", 28),"大连");
tm.put(new Student("赵六", 24),"上海");
tm.put(new Student("小强", 31),"沈阳");
//1、通过迭代器(键找值)
Iterator<Student> it=tm.keySet().iterator();
while(it.hasNext()){
Student s=it.next();
String str=tm.get(s);
System.out.println(s.getName()+"--"+s.getAge()+"--"+str);
}
System.out.println("---------------");
//通过增强for(键找值)
Set<Student> set=tm.keySet();
for(Student ss:set){
String s=tm.get(ss);
System.out.println(ss.getName()+"--"+ss.getAge()+"--"+s);
}
//2、增强for(键值对)
System.out.println("---------------");
Iterator<Map.Entry<Student, String>> it2=tm.entrySet().iterator();
while(it2.hasNext()){
Map.Entry<Student, String> s = it2.next();
Student student=s.getKey();
String string=s.getValue();
System.out.println(student.getName()+"--"+student.getAge()+"--"+string);
}
System.out.println("---------------");
//迭代器(键值对)
Set<Map.Entry<Student, String>> set2= tm.entrySet();
for(Map.Entry<Student, String> ss:set2){
Student s=ss.getKey();
String str=ss.getValue();
System.out.println(s.getName()+"--"+s.getAge()+"--"+str);
}
}
}
public class Student {
private String name;
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
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 int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
} |
|