在 Java 中对 HashTable 中的键进行排序
你不能用它的键对 HashTable 进行排序,但你可以拯救在方法 Collections.sort().
在此示例中,我们将键从 HashTable 复制到 ArrayList。密钥是通过 keySet(),然后调用 Collections.sort()它以新创建的 ArrayList 为参数,其中包含我们的 keys.
在此示例中,我们将键从 HashTable 复制到 ArrayList。密钥是通过 keySet(),然后调用 Collections.sort()它以新创建的 ArrayList 为参数,其中包含我们的 keys.
import java.util.ArrayList;输出:
import java.util.Collections;
导入 java.util.Hashtable;
import java.util.List;
import java.util.Map;
public class TriTreeMap {
public static void main(String[] args) {
//创建一个hashtable
Hashtableht = new Hashtable ();
//添加键值对
ht.put(d”, fourth”);
ht.put(a”, 第一”);
ht.put(c”, 第三”);
ht.put(e”, 第五”);
ht.put(b”, 第二”);
System.out.println(排序之前:”);
for (Map.Entryentry : ht.entrySet())
{
System.out.println(entry.getKey());
}
//使用从 hashtable
Listlistcles = new ArrayList (ht.keySet());
//sort arraylist
Collections.sort(listcles);
System.out.println(排序后:”);
for(String key:listcles)
System.out.println(cle);
}
}
排序前:
b
a
e
d
c
排序后:
a
b
c
d
e