【java编程】Map集合之TreeMap按学生姓名进行升序排序
2015-02-26 09:52
826 查看
import java.util.*; /*要对键值对进行排序,只能用TreeMap来排序 HashMap底层是哈希表,哈希表是随机的*/ class TreeMapDemo { public static void main(String[] args) { TreeMap<Student,String> tm = new TreeMap<Student,String>(new compl()); tm.put(new Student("wc",24),"shanghai"); tm.put(new Student("wa",26),"xinjiang"); tm.put(new Student("wb",25),"hubei"); tm.put(new Student("wd",28),"hunan"); Set<Map.Entry<Student,String>> entrySet=tm.entrySet(); Iterator<Map.Entry<Student,String>> it=entrySet.iterator(); while(it.hasNext()) { Map.Entry<Student,String> me=it.next(); Student stu=me.getKey(); String addr=me.getValue(); System.out.println(stu.getName()+":"+stu.getAge()+"-----"+addr); } } } //自建比较器实现按姓名排序 class compl implements Comparator<Student> { public int compare(Student s1,Student s2) { int num=s1.getName().compareTo(s2.getName()); if(num==0) return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge())); return num; } } class Student implements Comparable<Student>//实现Comparable方法让Student具备比较性 { private String name; private int age; Student(String name,int age) { this.name=name; this.age=age; } public String getName() { return name; } public int getAge() { return age; } //复写hashCode方法为哈希表判断重复元素使用 public int hashCode() { return this.name.hashCode()+age*20; } //复写equals方法 public boolean equals(Object obj) { if(!(obj instanceof Student)) throw new ClassCastException("类型不匹配!"); Student s=(Student)obj; return this.name.equals(s.getName()) && this.age==s.getAge(); } //复写compareTo方法 public int compareTo(Student s) { int num=new Integer(this.age).compareTo(new Integer(s.getAge())); if(num==0) return this.name.compareTo(s.getName()); return num; } }
相关文章推荐
- Java 使用TreeMap对学生对象的年龄进行升序排序。
- TreeMap练习:对学生对象的姓名进行升序排序
- TreeMap集合的应用根据学生的年龄或者姓名排序
- 要求从用户输入的多行文本中提取学生的姓名、学号及登录日期,并封装到 Student 类中作为类的私有属性。创建一个Student类型的对象数组,对学号进行 升序排序并输出。
- java如何对map进行排序详解(map集合的使用)
- 【java编程】Map集合之TreeMap字符串中字符出现次数
- java如何对map进行排序详解(map集合的使用)
- java如何对map进行排序详解(map集合的使用)
- 有5名学生保存在结构体数组中,编程按学生的成绩升序排序,按学生的姓名降序排序,按年龄从低到高排序, 成绩, 年龄
- 集合练习。学生信息包括学号、姓名、出生日期、性别。把N个学生的信息放入一个集合中。可以根据学号,对学生信息进行检索。并可以根据生日进行排序输出。
- java中使用TreeMap进行中文姓名排序
- C语言,有5名学生保存在结构体数组中,编程按学生的成绩升序排序,按学生的姓名降序排序,按年龄从低到高排序
- java如何对map进行排序详解(map集合的使用)
- 要求从用户输入的多行文本中提取学生的姓名、学号及登录日期,并封装到 Student 类中作为类的私有属性。创建一个 Student 类型的对象数组,对学号进行 升序排序并输出
- 用java编写TreeMap<Student,String>集合,存储的元素按照年龄进行排序
- java的Map集合中按value值进行排序输出的实例代码
- Java 往TreeSet集合中存储自定义对象学生,按照学生的年龄进行排序。
- C#例题:输入学生学号,姓名,分数,然后根据分数进行排序。这个题是用集合和结构体来做,与上一题不同。掌握基础知识很重要
- 有5名学生保存在结构体数组中,编程按学生的成绩升序排序,按学生的姓名降序排序,按年龄从低到高排序
- 有5名学生保存在结构体数组中,编程按学生的成绩升序排序,按学生的姓名降序排序,按年龄从低到高排序