如何从Java中的HashMap获取关键位置 [英] How to get key position from a HashMap in Java

查看:89
本文介绍了如何从Java中的HashMap获取关键位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得地图中的关键位置?如何查看奥迪和宝马的位置?

How can I get the key position in the map? How can I see on which position is "Audi" and "BMW"?

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Audi", 3);
map.put("BMW", 5);


推荐答案

正如其他答案所述,您需要使用类似的结构 java.util.LinkedHashMap中。 LinkedHashMap使用 LinkedEntrySet 在内部维护其键,这不正式提供顺序,而是按照使用的插入顺序进行迭代。

As other answers state you need to use a structure like java.util.LinkedHashMap. LinkedHashMap maintains its keys internally using a LinkedEntrySet, this does not formally provide order, but iterates in the insertion order used.

如果将 Map.keySet()传递给List实现,则可以使用 List.indexOf(Object)方法,无需在其他答案中编写任何额外代码。

If you pass the Map.keySet() into a List implementation you can make use of the List.indexOf(Object) method without having to write any of the extra code in the other answer.

Map<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("Audi", 3);
map.put("BMW", 5);
map.put("Vauxhall", 7);

List<String> indexes = new ArrayList<String>(map.keySet()); // <== Set to List

// BOOM !

System.out.println(indexes.indexOf("Audi"));     // ==> 0
System.out.println(indexes.indexOf("BMW"));      // ==> 1
System.out.println(indexes.indexOf("Vauxhall")); // ==> 2

这篇关于如何从Java中的HashMap获取关键位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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