浅谈java中的TreeMap 排序与TreeSet 排序
程序员文章站
2024-03-11 17:58:43
treemap:
package com;
import java.util.comparator;
import java.util.treemap;...
treemap:
package com; import java.util.comparator; import java.util.treemap; public class test5 { /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub treemap<string, string> tree = new treemap<string, string>( new comparator<object>() { @override public int compare(object o1, object o2) { // todo auto-generated method stub if(o1 == null || o2 == null){ return 0; } return o1.tostring().compareto(o2.tostring()); } } ); tree.put("k", "1"); tree.put("ba", "2"); tree.put("z", "3"); tree.put("d", "4"); tree.put("e", "5"); tree.put("an", "6"); tree.put("c", "7"); for(string str : tree.keyset()){ system.out.println(str); } } }
经测试默认是按照 key 进行排序的。
但是可以写对象比较器,进行自定义排序。
treeset : 自定义倒序排序,默认按照正序排序,1,2,3,4,5,6
package com; import java.util.comparator; import java.util.treeset; public class test6 { /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub treeset<object> tree = new treeset<object>(new comparator<object>() { @override public int compare(object o1, object o2) { // todo auto-generated method stub if(o1 == null || o2 == null){ return 0; } if(integer.parseint(o1.tostring()) > integer.parseint(o2.tostring())){ return -1; }else if(integer.parseint(o1.tostring()) < integer.parseint(o2.tostring())){ return 1; }else{ return 0; } } }); tree.add(4); tree.add(5); tree.add(6); tree.add(1); tree.add(2); tree.add(3); for(object o : tree){ system.out.println(o); } } }
以上这篇浅谈java中的treemap 排序与treeset 排序就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。