- public class MainClass {
- public static void main(String[] args) {
- Map<Person, Integer> tm = new TreeMap<Person, Integer>();
- tm.put(new Person("张三", 24), 15);
- tm.put(new Person("李四", 23), 8);
- tm.put(new Person("王五", 22), 23);
- tm.put(new Person("刘六", 21), 35);
- tm.put(new Person("田七", 25), 16);
- Set<Person> set = tm.keySet();
- Iterator<Person> i = set.iterator();
- Person p = null;
- if (i.hasNext()) {
- p = i.next();
- }
- while (i.hasNext()) {
- Person tmp = i.next();
- if (tm.get(p) < tm.get(tmp)) {
- p = tmp;
- }
- }
- System.out.println(p + "的值最大,为:" + tm.get(p));
- }
- }
- class Person implements Comparable<Person> {
- private String name;
- private int age;
- public Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- public int compareTo(Person person) {
- int result = 0;
- if (this.age < person.age) {
- result = -1;
- } else if (this.age > person.age) {
- result = 1;
- }
- return result;
- }
- public String toString() {
- return age + "岁的" + name;
- }
- }
复制代码 运行结果为
21岁的刘六的值最大,为:35
自己写得...迭代器每次取出比较找到最大的... |