Java TreeMap sort key value pair by key value

Introduction

To sort key value pair by key value we can use TreeMap in Java.

// Create a tree map.
TreeMap<String, Double> tm = new TreeMap<String, Double>();
    

Full source


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

public class Main {
  public static void main(String args[]) {

    // Create a tree map.
    TreeMap<String, Double> tm = new TreeMap<String, Double>();

    // Put elements to the map.
    tm.put("HTML", new Double(3434.34));
    tm.put("CSS", new Double(123.22));
    tm.put("Java", new Double(1378.00));
    tm.put("Javascript", new Double(99.22));
    tm.put("SQL", 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());
    }// w w w. j  ava  2  s .com
    System.out.println();

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

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



PreviousNext

Related