java中,map集合排序实例
来源:互联网 发布:淘宝足球 编辑:程序博客网 时间:2024/06/05 23:08
1.实体类
package test;
/**
* 学生实体类
* @author xf
*
*/
public class Student {
private String name;
private int avg;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAvg() {
return avg;
}
public void setAvg(int avg) {
this.avg = avg;
}
}
2.map集合排序实现类
package test;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* map集合排序
* @author xf
*
*/
public class MapKeyComparator implements Comparator<String> {
@Override
public int compare(String str1, String str2) {
int num=str1.compareTo(str2);
if(num>0){ //降序
return -1;
}else{
return 1;
}
/*if(num>0){ //升序
return 1;
}else{
return -1;
}*/
}
/**
* 使用 Map按key进行排序
* @param map
* @return
*/
public static Map<String, Student> sortMapByKeyStu(Map<String, Student> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, Student> sortMap = new TreeMap<String, Student>(
new MapKeyComparator());
sortMap.putAll(map);
return sortMap;
}
}
3.测试类
package test;
import java.util.HashMap;
import java.util.Map;
public class Test_sdgd {
public static void main(String[] args) {
try {
Map<String, Student> map = new HashMap<String, Student>();
map.put("2009", new Student());
map.put("2016", new Student());
map.put("2005", new Student());
map.put("2001", new Student());
map.put("2014", new Student());
map.put("2011", new Student());
map.put("2010", new Student());
map.put("2012", new Student());
map=MapKeyComparator.sortMapByKeyStu(map);
for (Map.Entry<String, Student> entry : map.entrySet()) {
System.out.println(entry.getKey());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
- java中,map集合排序实例
- JAVA中Map集合
- java中map排序
- Java中Map排序
- java中map排序
- java中map的种类区别及排序详解(map集合的使用)
- java中Map集合总结
- Java中Map集合详解
- Java中map集合框架
- Java集合框架之Map实例解析
- Java 实现Map集合排序功能
- java中的Map集合按Key排序
- java中Map集合的常用遍历方法及HashMap的应用实例
- java中Map集合的常用遍历方法及HashMap的应用实例
- java中Map集合的常用遍历方法及HashMap的应用实例
- java中Map集合的常用遍历方法及HashMap的应用实例
- 【Java基础】Map集合简介 排序的集合TreeMap
- Java中Map的排序
- ssh环境搭建(2)-config篇(spring4.2.6+struts2.5+hibernate5.1 )
- Fragment中setUserVisibleHint 方法调用问题
- Apache和Tomcat之间请求处理
- 【WebService】3.使用CXF开发WebService客户端
- Android小程序-乐学成语背景音乐(五)
- java中,map集合排序实例
- 修改Android系统中/system的读写权限
- socket
- php配置
- leetcode之全排列问题(Permutations)
- lintcode ---- 最长公共前缀
- Android Material Design 兼容库的使用详解
- SIP路由
- centOS下整合Tomcat和redis