关闭

TreeMap 排序

3672人阅读 评论(0) 收藏 举报

/*

比较函数类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"));
 }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:690849次
    • 积分:7948
    • 等级:
    • 排名:第2693名
    • 原创:75篇
    • 转载:247篇
    • 译文:0篇
    • 评论:64条
    文章分类
    最新评论