Java有序映射 [英] Java Ordered Map

查看:303
本文介绍了Java有序映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,是否有一个对象用于存储和访问键/值对,用于存储和访问键/值对,但可以返回键的有序列表和值的有序列表,以使键和值列表在同一个

In Java, Is there an object that acts like a Map for storing and accessing key/value pairs, but can return an ordered list of keys and an ordered list of values, such that the key and value lists are in the same order?

因此,作为一个解释的代码,我正在寻找一些行为像我的虚构OrderedMap:

So as explanation-by-code, I'm looking for something that behaves like my fictitious OrderedMap:

OrderedMap<Integer, String> om = new OrderedMap<>();
om.put(0, "Zero");
om.put(7, "Seven");

String o = om.get(7); // o is "Seven"
List<Integer> keys = om.getKeys();
List<String> values = om.getValues();

for(int i = 0; i < keys.size(); i++)
{
    Integer key = keys.get(i);
    String value = values.get(i);
    Assert(om.get(key) == value);
}


推荐答案

SortedMap 界面(实施 TreeMap )应该是您的朋友。

The SortedMap interface (with the implementation TreeMap) should be your friend.

该界面有以下方法:

  • keySet() which returns a set of the keys in ascending order
  • values() which returns a collection of all values in the ascending order of the corresponding keys

所以这个接口完全符合你的要求。但是,键必须具有有意义的顺序。否则,您可以使用 LinkedHashMap ,其中订单由插入订单决定。

So this interface fulfills exactly your requirements. However, the keys must have a meaningful order. Otherwise you can used the LinkedHashMap where the order is determined by the insertion order.

这篇关于Java有序映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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