黑马程序员技术交流社区
标题:
Map类型的容器中元素“6” ”5” ”3” ”1” ”2” ”4”进行排序。
[打印本页]
作者:
黑马-罗志强
时间:
2013-1-6 11:00
标题:
Map类型的容器中元素“6” ”5” ”3” ”1” ”2” ”4”进行排序。
对一个Map类型的容器中元素“6” ”5” ”3” ”1” ”2” ”4”进行排序。
Map中不是键值对吗?
用TreeMap可不可以啊.
作者:
夏振博
时间:
2013-1-6 16:12
不确定是否能解决你的问题!
将Map集合排序和反转.png
(14.19 KB, 下载次数: 38)
下载附件
2013-1-6 16:09 上传
作者:
熊永标
时间:
2013-1-6 16:44
package cn.javastudy.demo1;
import java.util.*;
public class StringBufferDemo {
public static void main(String[] args)
{
TreeMap<String, String> sort=new TreeMap<String,String>(new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
if(o1.equals(o2))
return 0;
if(o1.compareTo(o2)>0)
return -1;
else
{
return 1;
}
}});
sort.put("6", "6");
sort.put("5", "5");
sort.put("3", "3");
sort.put("1", "1");
sort.put("2", "2");
sort.put("4", "4");
System.out.println(sort);
}
}
复制代码
作者:
罗利华
时间:
2013-1-6 17:12
是的,Map中放的是key/value对,
可以这样排序,
public class TestSort {
public static void main(String[] args) {
TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();
map.put(6, 6);
map.put(5,5);
map.put(3,3);
map.put(1, 1);
map.put(2,2);
map.put(4,4);
Collection col = map.values();
Iterator it = col.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
注意:如果要排序中文的话,要自己创建一个类去实现Comparator。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2