当前位置:主页 > 软件编程 > JAVA代码 >

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

时间:2020-10-23 16:02:08 | 栏目:JAVA代码 | 点击:

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);
		}
	}

}

您可能感兴趣的文章:

相关文章