import java.util.HashMap;出力:
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) {
マップ<文字列,文字列>hmap = new HashMap<文字列,文字列>();
hmap.put("4", "4");
hmap.put("2", "two");
hmap.put("3", "three");
hmap.put("1", "one");
Set set = hmap.entrySet();
イテレータイテレータ = set.iterator();
System.out.println("並べ替え前:");
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
マップ sortedMap = new TreeMap(hmap);
Set set2 = sortedMap.entrySet();
イテレータ iterator2 = set2.iterator();
System.out.println("ソート後:");
while(iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
}
}
}
ソート前:
3: three
2: two
1: one
4: four
ソート後:
1: one
2: two
3: three
4: four
import java.util.Collections;Output:
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<文字列、文字列>sortHashMap(マップ<文字列、文字列>hmap){
リスト>list =
new LinkedList>( hmap.entrySet() );
Collections.sort( list, new Comparator>(){
public int compare
(Map.Entry<文字列、文字列>o1、Map.Entryです<文字列、文字列>o2 )
{
//2つのキーを比較する
return (o1.getKey()).compareTo( o2.getKey() );
}
});
//LinkedList
HashMapから新しいHashMapを作成します<文字列、文字列>hmapTriee = new LinkedHashMap<文字列、文字列>();
(Map.Entry<文字列、文字列>entry : list)
{
hmapTriee.put( entry.getKey(), entry.getValue() );
}
return hmapTriee;
}
public static void main(String[] args) {
final HashMap<文字列、文字列>hmap = new HashMap<文字列、文字列>();
hmap.put("4", "4");
hmap.put("2", "two");
hmap.put("3", "three");
hmap.put("1", "one");
System.out.println("ソート前: "+ hmap);
System.out.println("ソート後: "+sortHashMap(hmap));
}
}
ソート前: {3=three, 2=two, 1=one, 4=four}
ソート後: {1=one, 2=two, 3=three, 4=four}
Please disable your ad blocker and refresh the window to use this website.