Java——hashMap去重和排序
Posted tractors
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java——hashMap去重和排序相关的知识,希望对你有一定的参考价值。
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去重和排序的主要内容,如果未能解决你的问题,请参考以下文章