import java.util.HashMap;Sortie:
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class Triclés {
public static void main(String[] args) {
Map<String,String> hmap = new HashMap<String,String>();
hmap.put("4", "quatre");
hmap.put("2", "deux");
hmap.put("3", "trois");
hmap.put("1", "un");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
System.out.println("Avant le tri: ");
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Map sortedMap = new TreeMap(hmap);
Set set2 = sortedMap.entrySet();
Iterator iterator2 = set2.iterator();
System.out.println("Après le tri: ");
while(iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
}
}
}
Avant le tri:
3: trois
2: deux
1: un
4: quatre
Après le tri:
1: un
2: deux
3: trois
4: quatre
import java.util.Collections;Sortie:
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Triclés {
public static HashMap<String, String> trierHashMap(Map<String, String> hmap){
List<Map.Entry<String, String>> list =
new LinkedList<Map.Entry<String, String>>( hmap.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<String, String>>(){
public int compare
(Map.Entry<String, String>o1, Map.Entry<String, String> o2 )
{
//comparer deux clés
return (o1.getKey()).compareTo( o2.getKey() );
}
});
//créer une nouvelle HashMap à partir de LinkedList
HashMap<String, String> hmapTriee = new LinkedHashMap<String, String>();
for (Map.Entry<String, String> entry : list)
{
hmapTriee.put( entry.getKey(), entry.getValue() );
}
return hmapTriee;
}
public static void main(String[] args) {
final HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("4", "quatre");
hmap.put("2", "deux");
hmap.put("3", "trois");
hmap.put("1", "un");
System.out.println("Avant le tri: "+ hmap);
System.out.println("Après le tri: "+trierHashMap(hmap));
}
}
Avant le tri: {3=trois, 2=deux, 1=un, 4=quatre}
Après le tri: {1=un, 2=deux, 3=trois, 4=quatre}
Please disable your ad blocker and refresh the window to use this website.