56

我有

LinkedHashMap<String, List<String>> hMap;

我想List<String>位置而不是关键。

我不想使用迭代。

有没有其他方法可以根据 index 获取 Value ?

4

5 回答 5

61

您无法获得Map基于索引的值,Maps 只是不那样工作。一种解决方法是根据您的值创建一个新列表并根据索引获取值。

LinkedHashMap<String, List<String>> hMap;
List<List<String>> l = new ArrayList<List<String>>(hMap.values());
l.get(0);
于 2012-11-27T10:23:35.180 回答
22
public List<String> getByIndex(LinkedHashMap<String, List<String>> hMap, int index){
   return (List<String>) hMap.values().toArray()[index];
}
于 2012-11-27T10:23:25.493 回答
15

您可能需要考虑使用另一个类来存储您的数据,或者为linkedHashMap 编写一个扩展。就像是

//this is pseudo code
public class IndexedLinkedHashMap<K,V> extends LinkedHashMap{

HashMap<int,K> index;
int curr = 0;

    @Override
    public void add(K key,V val){
        super.add(key,val);
        index.add(curr++, key);
    }

    public V getindexed(int i){
        return super.get(index.get(i));
    }

}
于 2012-11-27T10:32:09.743 回答
9

正如 Kevin Bowersox 所说,这很简单

List<String> result = (List<String>) hMap.values().toArray()[position];

但应该注意的是,这仍然会通过使用 .toArray() 进行迭代。这是一个简单的语句,我不确定是否有一个性能更好的语句,但请注意复杂性不是 log(n)(如 B* 的索引访问),而只是 n。由于 LinkedHashMap 是基于 LinkedList 的,所以没有办法随机访问元素,只能按顺序访问。

转换为 List 是不可避免的邪恶,因为 .toArray() 遵循返回 Object 而不是泛型数据类型的古老概念。

虽然这可能不是地图的主要概念,但 LinkedHashMap 不仅仅是地图。它扩展了 HashMap,并且作为一个扩展类,引入支持该类特性的其他方法非常好。

于 2014-03-28T14:32:51.457 回答
4

标准 Java Collections API 中没有直接的 DS 来提供索引映射。但是,以下内容应该可以让您获得结果:

// An ordered map
Map<K, V> map = new LinkedHashMap<K, V>();
// To create indexed list, copy the references into an ArrayList (backed by an array)
List<Entry<K, V>> indexedList = new ArrayList<Map.Entry<K, V>>(map.entrySet());
// Get the i'th term
<Map.Entry<K,V>> entry = indexedList.get(index);
K key = entry.getKey();
V value = entry.getValue();

您可能仍希望将地图中的数据持久性问题与检索分开。

更新:或使用Apache Commons 的LinkedMap

于 2013-08-11T04:49:14.740 回答