Java HashMap convert to TreeMap to sort key-value pair by keys

Description

Java HashMap convert to TreeMap to sort key-value pair by keys

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Main {

  public static void main(String[] a) {
    Map<String, String> yourMap = new HashMap<String, String>();
    yourMap.put("style", "CSS");
    yourMap.put("tag", "HTML");
    yourMap.put("backend", "Java");

    System.out.println(yourMap);// w  ww .  j  a  v  a2s .  c  o m
    
    Map<String, String> sortedMap = new TreeMap<String, String>(yourMap);

    System.out.println(sortedMap);
  }
}



PreviousNext

Related