Use a comparator to sort accounts by last name. : Comparator Interface « Collections « Java Tutorial

import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

class TComp implements Comparator<String> {
  public int compare(String a, String b) {
    int i, j, k;
    String aStr, bStr;

    aStr = a;
    bStr = b;

    i = aStr.lastIndexOf(' ');
    j = bStr.lastIndexOf(' ');

    k = aStr.substring(i).compareTo(bStr.substring(j));
    if (k == 0) // last names match, check entire name
      return aStr.compareTo(bStr);
      return k;


class TreeMapDemo2 {
  public static void main(String args[]) {
    TreeMap<String, Double> tm = new TreeMap<String, Double>(new TComp());

    tm.put("J D", new Double(3434.34));
    tm.put("T S", new Double(123.22));
    tm.put("J B", new Double(1378.00));
    tm.put("T H", new Double(99.22));
    tm.put("R S", new Double(-19.08));

    Set<Map.Entry<String, Double>> set = tm.entrySet();

    for (Map.Entry<String, Double> me : set) {
      System.out.print(me.getKey() + ": ");

    double balance = tm.get("A");
    tm.put("A", balance + 1000);

    System.out.println("A's new balance: " + tm.get("A"));

9.40.Comparator Interface
9.40.1.System-Defined Comparable Classes
9.40.2.Writing Your own Comparator
9.40.3.Getting reverse order comparator
9.40.4.Implementing a Comparator for a class
9.40.5.Use a custom comparator.
9.40.6.Sort an array of strings in reverse order.
9.40.7.Sort an array of strings, ignore case difference.
9.40.8.Use a comparator to sort accounts by last name.
9.40.9.Comparator uses a Collator to determine the proper, case-insensitive lexicographical ordering of two strings.
9.40.10.Calendar Comparator
9.40.11.Invertible Comparator