Java TreeMap create with custom comparator for custom object

Introduction

To create TreeMap with custom comparator for custom object in Java

// Compare last whole words in two strings.  
class TComp implements Comparator<String> {
  public int compare(String aStr, String bStr) {
    int i, j, k;//from   w  ww. jav  a  2  s. c om

    // Find index of beginning of last name.
    i = aStr.lastIndexOf(' ');
    j = bStr.lastIndexOf(' ');

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

  // No need to override equals.
}

Full source


// Use a comparator to sort accounts by last name.  
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

// Compare last whole words in two strings.  
class TComp implements Comparator<String> {
  public int compare(String aStr, String bStr) {
    int i, j, k;/*from   w ww . j av  a2 s.c o m*/

    // Find index of beginning of last name.
    i = aStr.lastIndexOf(' ');
    j = bStr.lastIndexOf(' ');

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

  // No need to override equals.
}

public class Main {
  public static void main(String args[]) {
    // Create a tree map.
    TreeMap<String, Double> tm = new TreeMap<String, Double>(new TComp());

    // Put elements to the map.
    tm.put("HTML DEF", new Double(1234.34));
    tm.put("CSS XYZ", new Double(2222.22));
    tm.put("Java YOU", new Double(3333.00));
    tm.put("Javascript HTML", new Double(99.22));
    tm.put("SQL GOOD", new Double(-19.08));

    // Get a set of the entries.
    Set<Map.Entry<String, Double>> set = tm.entrySet();

    // Display the elements.
    for (Map.Entry<String, Double> me : set) {
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
    }
    System.out.println();

    // Deposit 1000 into HTML's account.
    double balance = tm.get("HTML DEF");
    tm.put("HTML DEF", balance + 1000);

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



PreviousNext

Related