按已设置的顺序迭代 HashMap

Iterating HashMap on order it has been set(按已设置的顺序迭代 HashMap)
本文介绍了按已设置的顺序迭代 HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经按特定顺序设置了 HashMap,但它以奇怪的顺序迭代!

I've set a HashMap on certain order but it is iterated on a strange order!

请考虑以下代码:

HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", "1");
map.put("Name", "the name");
map.put("Sort", "the sort");
map.put("Type", "the type");

...

for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
}

结果:

Name: the name
Sort: the sort
Type: the type
ID: 1

我需要对其进行迭代,以便我放置条目.任何帮助将不胜感激.

I need to iterate it in order i've put the entries. Any help will be appreciated.

推荐答案

顺序取决于你插入的键中 hashCode() 函数的结果,除非你做了一些奇怪的事情,将主要是随机的(但一致).您正在寻找的是一个排序的地图,例如 LinkedHashMap

The order depends on the result of the hashCode() function in the keys you are inserting which, unless you did something strange, is going to be mostly random (but consistent). What you are looking for is a sorted map such as a LinkedHashMap

如果您对详细信息感兴趣,请在此处了解 哈希表 的工作原理.

Check out a little bit about how hashtables work here if you are interested in the details.

这篇关于按已设置的顺序迭代 HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)