Studyon Minte9.com
Java SE




Sort (TreeMap)



TreeMap - Sort

package testexample; import java.util.*; public class Test { public static void main(String[] args) { final TreeMap<Integer, String> data = new TreeMap<Integer, String>(); data.put(1, "50"); data.put(2, "70"); data.put(3, "60"); for(Object i : data.keySet()) { System.out.println(i + ":" + data.get(i)); } // Outputs: 1:50 , 2:70 , 3:60 // --- Look Here --- // TreeMap<Integer, String> data2 = new TreeMap<Integer, String>( new Comparator<Integer>(){ public int compare(Integer i1, Integer i2) { return data.get(i1).compareTo(data.get(i2)); } } ); data2.putAll(data); for(Object i : data2.keySet()) { System.out.println(i + ":" + data2.get(i)); } // Outputs: 1:50 , 3:60 , 2:70 } }
  TreeMap (Properties) - Sort
package testexample; import java.util.*; public class Test { public static void main(String[] args) { String[][] data = new String[][] { {"Juventus", "1"}, {"Fiorentina", "3"}, {"Milan", "2"}, }; final TreeMap<Integer, Properties> teams = new TreeMap<Integer, Properties>(); for(int i=0; i<data.length; i++) { Properties p = new Properties(); p.put("team", data[i][0]); p.put("points", data[i][1]); teams.put(i, p); } for(Object i : teams.keySet()) { Properties p = teams.get(i); System.out.println(p.getProperty("team") + ":" + p.getProperty("points")); } // Outputs: Juventus:1 , Fiorentina:3 , Milan:2 // --- Look Here --- // TreeMap<Integer, Properties> teams2 = new TreeMap<Integer, Properties>( new Comparator<Integer>() { public int compare(Integer i1, Integer i2) { String s1 = teams.get(i1).getProperty("points") + teams.get(i1).getProperty("team"); String s2 = teams.get(i2).getProperty("points") + teams.get(i1).getProperty("team"); return s2.compareTo(s1); // --- Sort DESC --- // } } ); teams2.putAll(teams); for(Object i : teams2.keySet()) { Properties p = teams2.get(i); System.out.println(p.getProperty("team") + ":" + p.getProperty("points")); } // Outputs: Fiorentina:3 , Milan:2 , Juventus:1 // --- Look Here --- // } }