码迷,mamicode.com
首页 > 编程语言 > 详细

Java——hashMap去重和排序

时间:2019-07-26 01:26:36      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:class   asn   entryset   compare   北京   string   vat   ring   pareto   

hashMap去重/排序:

  1)map集合需要键名唯一,hashmap是通过hashcode和eauals来控制键名唯一;

  2)从写Comparable中的compareTo方法来对map集合排序;

  1、实体类:

public class Student implements Comparable<Student>{
    private String name;
    private int age;
    public Student(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 "Student{" +
                "name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ‘}‘;
    }

    @Override
    public int compareTo(Student s) {
        int num = new Integer(this.getAge()).compareTo(new Integer(s.getAge()));
        if (num == 0) {
            num = this.getName().compareTo(s.getName());
        }
        return num;
    }

    @Override
    public int hashCode() {
        System.out.println(this.name+".....hashCode");
        return this.getName().hashCode();
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Student)) return false;
        Student s = (Student) obj;
        System.out.println(this.name+this.age+"..equals..");
        return this.getName().equals(s.getName()) && this.getAge() == s.getAge();
    }
}

  2、测试类;

public class Test {
    public static void main(String[] args) {
        Map<Student, String> ms = new HashMap<Student, String>();
        ms.put(new Student("张三", 10), "北京");
        ms.put(new Student("张五", 12), "南京");
        ms.put(new Student("张五", 12), "北京");
        ms.put(new Student("张五", 13), "北京");

        Set<Map.Entry<Student, String>> entries = ms.entrySet();
        for (Iterator<Map.Entry<Student, String>> it2 = entries.iterator(); it2.hasNext(); ) {
            Map.Entry<Student, String> next = it2.next();
            System.out.println(next.getKey() + "====" + next.getValue());
        }
    }
}

 

Java——hashMap去重和排序

标签:class   asn   entryset   compare   北京   string   vat   ring   pareto   

原文地址:https://www.cnblogs.com/Tractors/p/11247592.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!