`
gallop_liu
  • 浏览: 109283 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

Java中使用TreeMap将Map的KeySet排序

 
阅读更多

使用TreeMap简单地HashMap的key进行排序,使用ArrayList对HashMap的value排序。

分别使用Comparator接口和Comparable接口实现key的排序。

package com.inspiration.examples.collection.sort;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Collections;

import java.util.Comparator;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.TreeMap;

import java.util.Map.Entry;

public class SortExample {

public static void listSort() {

List<Student> stuList = new ArrayList<Student>();

Student s1 = new Student(1, "wang");

Student s2 = new Student(2, "li");

stuList.add(s1);

stuList.add(s2);

Collections.sort(stuList);

for (Student stu : stuList) {

System.out.println(stu);

}

// map sort which implements the Comparable Interface

public static void mapKeySetSort() {

Map<Student, Integer> hashMap = new HashMap<Student, Integer>();

for (int i = 0; i < 100; i++) {

Student stu = new Student(i, "wang" + i);

hashMap.put(stu, i);

}

/*

* System.out.println("the hashMap out put----"); Set<Student>

* set=hashMap.keySet(); for(Student stu:set){ System.out.println(stu);

* }

*/

System.out.println("the treeMap out put----");

TreeMap<Student, Integer> treeMap = new TreeMap<Student, Integer>(

hashMap);

Set<Student> set2 = treeMap.keySet();

for (Student stu : set2) {

System.out.println(stu);

}

// map sort which implements the Comparator Interface

public static void mapKeySetSort2() {

Map<Teacher, Integer> hashMap = new HashMap<Teacher, Integer>();

for (int i = 0; i < 100; i++) {

Teacher tea = new Teacher(i, "wang" + i);

hashMap.put(tea, i);

}

/*

* System.out.println("the hashMap out put----"); Set<Teacher>

* set=hashMap.keySet(); for(Teacher tea:set){ System.out.println(tea);

* }

*/

System.out.println("the treeMap out put----");

TreeMap<Teacher, Integer> treeMap = new TreeMap<Teacher, Integer>(

new TeacherComparator());

treeMap.putAll(hashMap);

Set<Teacher> set2 = treeMap.keySet();

for (Teacher tea : set2) {

System.out.println(tea);

}

public static void sortValues() {

Map<String, Integer> keyfreqs = new HashMap<String, Integer>();

keyfreqs.put("w", 1);

keyfreqs.put("b", 2);

ArrayList<Entry<String, Integer>> l = new ArrayList<Entry<String, Integer>>(

keyfreqs.entrySet());

Collections.sort(l, new Comparator<Map.Entry<String, Integer>>() {

public int compare(Map.Entry<String, Integer> o1,

Map.Entry<String, Integer> o2) {

return (o1.getValue() - o2.getValue());

}

});

for (Entry<String, Integer> e : l) {

System.out.println(e.getKey() + "::::" + e.getValue());

}

public static void main(String[] args) {

// listSort();

// System.exit(1);

// mapSort();

// mapKeySetSort2();

}

package com.inspiration.examples.collection.sort;

public class Student implements Comparable<Student>{

private int id;

private String name;

public Student(int id, String name) {

super();

this.id = id;

this.name = name;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Override

public int compareTo(Student o) {

// return o.id-this.id;

return this.id-o.id;

}

@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + id;

return result;

}

@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

Student other = (Student) obj;

if (id != other.id)

return false;

return true;

}

@Override

public String toString() {

return "Student [id=" + id + ", name=" + name + "]";

}

package com.inspiration.examples.collection.sort;

public class Teacher {

private int id;

private String name;

public Teacher(int id, String name) {

super();

this.id = id;

this.name = name;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + id;

return result;

}

@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

Teacher other = (Teacher) obj;

if (id != other.id)

return false;

return true;

}

@Override

public String toString() {

return "Teacher [id=" + id + ", name=" + name + "]";

}

package com.inspiration.examples.collection.sort;

import java.util.Comparator;

public class TeacherComparator implements Comparator<Teacher>{

@Override

public int compare(Teacher o1, Teacher o2) {

return o1.getId()-o2.getId();

}

TreeMap本身使用红黑树算法实现。

原文地址 http://my.oschina.net/forrest420/blog/96644

分享到:
评论

相关推荐

    java用treemap统计单词出现的个数

    TreeMap是Java集合框架中的一种Map实现,它实现了SortedMap接口,能够根据键的自然顺序或自定义的比较器对键进行排序。在本例中,我们使用TreeMap来统计单词出现的次数,并按照字母表顺序输出。 知识点2:Java比较...

    浅谈java中的TreeMap 排序与TreeSet 排序

    在Java编程语言中,`TreeMap` 和 `TreeSet` 是两种基于红黑树数据结构实现的集合类,它们都提供了自动排序的功能。本文将详细探讨 `TreeMap` 和 `TreeSet` 的排序机制以及如何自定义排序规则。 首先,`TreeMap` 是...

    TreeMap in Java_java_treemap_

    1. **插入元素**:使用`put()`方法将键值对插入到`TreeMap`中。例如,`map.put(key, value)`会将`key`与`value`关联。 2. **获取元素**:使用`get()`方法通过键来获取对应的值,如`map.get(key)`。 3. **删除元素*...

    java中map的使用实例

    本篇文章将深入讲解Map的使用实例,包括插入、读取和遍历操作,以及HashMap、LinkedHashMap和TreeMap这三种常见的Map实现类之间的区别。 首先,让我们看看如何创建和插入键值对。在Java中,我们通常通过调用`put()`...

    java中map集合的用法

    本文将详细介绍Java中Map集合的用法。 **1. Map接口概述** Map接口位于`java.util`包下,它定义了一些基本的操作方法,如put、get、remove等。Map集合中常用的实现类有HashMap、TreeMap、LinkedHashMap等,它们各自...

    java-遍历map

    本文将深入探讨如何在Java中使用`keySet`方法来遍历`Map`集合,以及相关的知识点。 ### 一、Java Map接口简介 `Map`接口是Java集合框架的一部分,它提供了存储和检索唯一键对象及其对应的值对象的方法。一个`Map`...

    java中map集合的用法.doc

    使用`put()`方法将键值对放入Map中,如: ```java map.put("sa", "dd"); ``` 3. **获取值**: 通过键来获取对应的值,可以使用`get()`方法: ```java String str = map.get("sa").toString(); ``` 4. **...

    java Map 遍历方法

    本篇文章将详细介绍几种常用的遍历`Map`的方法,包括使用传统迭代器(Iterator)、增强型for循环(For-Each循环)以及通过键集(Key Set)进行遍历。 #### 一、使用Iterator遍历Map 1. **通过`entrySet()`获取迭代...

    java中map集合的用法.pdf

    Java提供了多种Map实现,如HashMap、TreeMap、LinkedHashMap等,每种实现有不同的性能特性和排序规则。HashMap是无序的,基于哈希表实现;TreeMap是有序的,基于红黑树实现;LinkedHashMap保持插入顺序或者访问顺序...

    JavaMap.rar_arraylist map_collection_java map_javamap_地图 java

    在Java中,"javamap"和"地图_java"可能是指使用Map类来模拟现实世界中的地理地图,例如通过键表示地理位置,值表示该地点的信息。这涉及到自定义类作为键值对中的元素类型,以及如何设计键值对以适应特定需求的问题...

    Java Map 集合类简介

    1. 是否需要线程安全性:如果在多线程环境中使用,可以选择HashTable或ConcurrentHashMap。 2. 数据排序:TreeMap提供了自然排序或自定义排序,而HashMap和LinkedHashMap则是无序的。 3. 访问效率:HashMap通常具有...

    java中MAp介绍

    ### Java中的Map接口详解 #### 一、Map接口概述 Map接口是Java集合框架中的一个核心接口,它并不属于`Collection`接口体系。Map的主要功能是存储键值对(key-value pairs),其中键(key)不允许重复,而值(value...

    Java Map 按Key排序实例代码

    总的来说,Java中对Map的Key进行排序通常有两种方式:一是使用支持排序的Map实现类如TreeMap,二是将HashMap的Key集合转换为List或TreeSet,然后进行排序。通过这种方式,我们可以灵活地根据需求调整Map中元素的顺序...

    java中Map映射机制

    在选择Map的具体实现时,Java提供了一些内置的类,如HashMap、TreeMap、LinkedHashMap等,它们各自有不同的特性和使用场景。HashMap提供快速的随机访问,TreeMap则按照键的自然顺序或自定义比较器进行排序,而...

    java map集合

    Map接口是Java Collections Framework的重要组成部分,提供了多种实现类,如HashMap、TreeMap、LinkedHashMap等,每种实现类都有其特定的特性和使用场景。 HashMap是最常用的Map实现,它不保证元素的顺序,允许null...

    重要知识java中map集合的用法.pdf

    Map 集合是 key-value 的形式存放的,可以使用 `put()` 方法将键值对添加到 Map 中。例如:`map.put("sa", "dd");` 3. 从 Map 中取值 可以使用 `get()` 方法从 Map 中获取指定键对应的值。例如:`String str = map...

    java集合MAP三种遍历

    本文将详细介绍Java中Map集合的三种遍历方法及其应用场景、优缺点等,帮助读者更好地理解和掌握Map的使用技巧。 ### 一、Map简介 `Map`接口是Java集合框架的一部分,它提供了基于键值对的数据存储方式。常见的实现...

    金陵科技学院软件院大二上Java高级1212Map.docx

    以上就是关于Java中Map的使用,特别是HashMap和TreeMap的基本操作。理解这些概念和方法对于处理键值对的数据结构至关重要。通过实践这些示例,你可以更熟练地在Java项目中运用Map接口及其实现类。

Global site tag (gtag.js) - Google Analytics