如何从迭代器()中以正确的顺序获取元素 [英] How to get the elements in correct order from iterator()

查看:152
本文介绍了如何从迭代器()中以正确的顺序获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的代码,用于将数据存储到HashMap中,并使用迭代器显示数据。

  public static void main(String args []){
HashMap< String,String> hm = new HashMap< String,String>();
hm.put(aaa,111);
hm.put(bbb,222);
hm.put(ccc,333);
hm.put(ddd,444);
hm.put(eee,555);
hm.put(fff,666);

Iterator iterator = hm.keySet()。iterator();

while(iterator.hasNext()){
String key =(String)iterator.next();
String val = hm.get(key);

System.out.println(key ++ val);






$ b

但它并不显示我的顺序存储。有人能告诉我我哪里错了吗?我如何获得订单中的元素?

解决方案

A HashMap 没有保证顺序:


这个类不能保证地图;

使用LinkedHashMap


Map接口的哈希表和链表实现可预测的迭代顺序。



Here is my code to store the data into HashMap and display the data using iterator

public static void main(String args[]) {
    HashMap<String, String> hm = new HashMap<String, String>();
    hm.put("aaa", "111");
    hm.put("bbb", "222");
    hm.put("ccc", "333");
    hm.put("ddd", "444");
    hm.put("eee", "555");
    hm.put("fff", "666");

    Iterator iterator = hm.keySet().iterator();

    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        String val = hm.get(key);

        System.out.println(key + " " + val);
    }
}

But it is not displaying in the order in which I stored. Could someone please tell me where am I going wrong? How can I get the elements in the order?

解决方案

A HashMap has no guaranteed order:

This class makes no guarantees as to the order of the map;

Use a LinkedHashMap.

Hash table and linked list implementation of the Map interface, with predictable iteration order.

这篇关于如何从迭代器()中以正确的顺序获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆