美文网首页
TreeMap排序

TreeMap排序

作者: _MrWhite | 来源:发表于2020-02-19 00:51 被阅读0次
    public class TreeMapTest1 {
        public static void main(String[] args) {
            Map<User,String> treeMap = new TreeMap();
            User user = new User("zhangsan", 18, 1000);
            User user2 = new User("lisi", 20, 1000);
            User user3 = new User("wangwu", 30, 500);
            treeMap.put(user, "张三");
            treeMap.put(user2, "李四");
            treeMap.put(user3, "王五");
            Set<Map.Entry<User, String>> entries = treeMap.entrySet();
            for (Map.Entry<User, String> entry : entries) {
                System.out.println(entry.getKey() + "---------" + entry.getValue());
            }
        }
    }
    
    class User implements Comparable<User> {
        String name;
        int age;
        double salary;
    
        public User() {
        }
    
        public User(String name, int age, double salary) {
            this.name = name;
            this.age = age;
            this.salary = salary;
        }
    
    
        @Override
        public int compareTo(User o) {
            if (this.salary > o.salary) {  //递增模式反之递减
                return 1;
            } else if (this.salary < o.salary) {
                return -1;
            } else {
                if (this.age > o.age) {
                    return 1;
                } else if (this.age < o.age) {
                    return -1;
                } else {
                    return 0;
                }
            }
        }
    
        @Override
        public String toString() {
            return this.name + "-" + this.age + "-" + this.salary;
        }
    }
    

    相关文章

      网友评论

          本文标题:TreeMap排序

          本文链接:https://www.haomeiwen.com/subject/bkdofhtx.html