MAC*_*MAC 45 java android linkedhashmap
我有
LinkedHashMap<String, List<String>> hMap;
Run Code Online (Sandbox Code Playgroud)
我想List<String>通过位置而不是关键.
我不想使用迭代.
有没有其他方法可以根据索引获得价值?
Per*_*ror 49
你不能得到Map基于索引的值,Map只是不这样做.解决方法是根据您的值创建一个新列表,并根据索引获取值.
LinkedHashMap<String, List<String>> hMap;
List<List<String>> l = new ArrayList<List<String>>(hMap.values());
l.get(0);
Run Code Online (Sandbox Code Playgroud)
Kev*_*sox 16
public List<String> getByIndex(LinkedHashMap<String, List<String>> hMap, int index){
return (List<String>) hMap.values().toArray()[index];
}
Run Code Online (Sandbox Code Playgroud)
小智 12
您可能想要考虑使用另一个类来存储数据,或者编写一个扩展到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));
}
}
Run Code Online (Sandbox Code Playgroud)
正如Kevin Bowersox所说,这很简单
List<String> result = (List<String>) hMap.values().toArray()[position];
Run Code Online (Sandbox Code Playgroud)
但应该注意的是,这仍将通过使用.toArray()进行迭代.这是一个简单的陈述,我不确定是否有更好的性能,但要注意复杂性不是log(n)(如B*情况下的索引访问),但只是n.由于LinkedHashMap基于LinkedList,因此无法按顺序随机访问元素.
对于List的强制转换是不可避免的恶,因为.toArray()遵循返回Object而不是通用数据类型的古老概念.
虽然这可能不是地图的主要概念,但LinkedHashMap不仅仅是一张地图.它扩展了HashMap,作为一个扩展类,带来支持该类特性的其他方法是完美的.
标准 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();
Run Code Online (Sandbox Code Playgroud)
您可能仍然希望保留映射中与检索分开的数据持久性问题。
更新:或者使用Apache Commons 中的LinkedMap 。
| 归档时间: |
|
| 查看次数: |
80474 次 |
| 最近记录: |