TREEMAP:
package com;
Import Java.util.Comparator;
Import Java.util.TreeMap;
public class Test5 {
/**
* @param args */public
static void Main (string[] args) {
//TODO Auto-gener Ated 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);}}}
After testing, the default is sorted by KEY.
However, you can write the object comparer to customize the sort.
TreeSet: custom reverse order, by default sorted by positive order, 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-gener Ated 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);}}}
Above this article on the TreeMap sorting and TreeSet in Java is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.