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()); } } }
原文地址:https://www.cnblogs.com/Tractors/p/11247592.html
时间: 2024-09-30 15:06:20