TreeMap用法 排序 示例

TreeMap类通过使用树来实现Map接口.TreeMap提供了按排序顺序存储关键字/值对的有效手段,同时允许快速检索。不像散列映射,树映射保证它的元素按照关键字升序排序。


import java.util.*;
class TreeMapDemo{
public static void main(String[] args)
{
//Creat a tree map
TreeMap tm = new TreeMap();

//Put elements to the map
tm.put("Evan",new Double(12345.77));
tm.put("Rose",new Double(78777));
tm.put("Magic",new Double(-99.10));
tm.put("Mike",new Double(100.00));
tm.put("Sue",new Double(17.15));

//Get a set of entries
Set set = tm.entrySet();

//Get an iterator
Iterator i = set.iterator();

//Display elements
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
System.out.println(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();

//Deposit 1000 into Evan's account
double balance = ((Double)tm.get("Evan")).doubleValue();
tm.put("Evan",new Double(balance + 1000));
System.out.println("Evan's new balance : " + tm.get("Evan"));
}
}



*******************************************
比较函数类TComp比较两个包含姓和名的字符串。它首先比较姓,具体是这样做的,首先寻找每一个字符串中最后一个空格的下标,然后比较从这个位置开始的每一个元素的子字符串。当两个字符串中姓完全相等时,再比较两个名。这样就形成了先按姓排序,在姓相同的情况下再按名字进行排序的树型映射。

//Use a comparator to sort accounts by last name.
import java.util.*;
//Compare last whole words in two strings.
class TComp implements Comparator{
public int compare(Object a,Object b){
int i,j,k;
String strA,strB;

strA = (String)a;
strB = (String)b;

//find index of beginning of last name
i = strA.lastIndexOf(' ');
j = strB.lastIndexOf(' ');
k = strA.substring(i).compareTo(strB.substring(j));
if(k==0) //last name match,check entire name
return strA.compareTo(strB);
else
return k;
}
//no need to override equals
}
public class TreeMapDemo2{
public static void main(String[] args)
{
//Create a tree map.
TreeMap tm = new TreeMap(new TComp());

//Put elements to the map.
tm.put("Sue Yuan",new Double(17.15));
tm.put("Jiahui Sheng",new Double(78777));
tm.put("Huajiang Chen",new Double(12345.77));
tm.put("Magic Ya",new Double(-99.10));
tm.put("Quanbing Chen",new Double(100.00));

//Get a set of the entries.
Set set = tm.entrySet();

//Get an iterator.
Iterator i = set.iterator();

//Display elements.
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
System.out.println(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();

//Deposit 1000 into Jiahui Sheng's account
double balance = ((Double)tm.get("Jiahui Sheng")).doubleValue();
tm.put("Jiahui Sheng",new Double(balance + 1000));
System.out.println("Jiahui Sheng's new balance : " + tm.get("Jiahui Sheng"));
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值