1.map集合需要键名唯一,hashmap是通过hashcode和eauals来控制键名唯一;
2.从写Comparable中的compareTo方法来对map集合排序;
实体类:
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();
}
}
测试类;
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());
}
}
}
以上就是HashMap去重和排序的方法,大家如果对此比较感兴趣,想了解更多相关知识,不妨来关注一下极悦的Java基础教程,里面的课程内容丰富,由浅到深,通俗易懂,适合没有基础的小白学习,希望对大家能够有所帮助。
你适合学Java吗?4大专业测评方法
代码逻辑 吸收能力 技术学习能力 综合素质
先测评确定适合在学习