Java TreeMap sort last name then first name via custom comparator

Introduction

Sort last name then first name via custom comparator and TreeMap in Java


// Use thenComparing() to sort by last, then first name.  
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;  
  
// A comparator that compares last names.  
class CompLastNames implements Comparator<String> {  
  public int compare(String aStr, String bStr) {  
    int i, j;  /*from w ww. j a  va2 s  .  c  o  m*/
  
    // Find index of beginning of last name. 
    i = aStr.lastIndexOf(' ');  
    j = bStr.lastIndexOf(' ');  
  
    return aStr.substring(i).compareToIgnoreCase(bStr.substring(j));  
  }  
}  

// Sort by entire name when last names are equal.
class CompThenByFirstName implements Comparator<String> {
  public int compare(String aStr, String bStr) {
    int i, j;  

    return aStr.compareToIgnoreCase(bStr);  
  }  
}
  
public class Main {  
  public static void main(String args[]) {  
    // Use thenComparing() to create a comparator that compares
    // last names, then compares entire name when last names match.
    CompLastNames compLN = new CompLastNames();
    Comparator<String> compLastThenFirst =
                         compLN.thenComparing(new CompThenByFirstName());

    // Create a tree map. 
    TreeMap<String, Double> tm =
                         new TreeMap<String, Double>(compLastThenFirst);  
      
    // Put elements to the map. 
    tm.put("HTML DEF", new Double(1234.34));  
    tm.put("CSS ABC", new Double(3333.22));  
    tm.put("Java XYZ", new Double(1234.00));  
    tm.put("Javascript AAA", new Double(99.22));  
    tm.put("SQL FGH", 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