I have
LinkedHashMap<String, List<String>> hMap;
我希望根据索引而不是键获取List<String>
。
我不想使用迭代。
是否有其他方法根据索引获取值?
I have
LinkedHashMap<String, List<String>> hMap;
我希望根据索引而不是键获取List<String>
。
我不想使用迭代。
是否有其他方法根据索引获取值?
您无法基于索引获取 Map
的值,Map
并不按照这种方式工作。一种解决方法是从您的值中创建一个新列表,并基于索引获取该值。
LinkedHashMap<String, List<String>> hMap;
List<List<String>> l = new ArrayList<List<String>>(hMap.values());
l.get(0);
public List<String> getByIndex(LinkedHashMap<String, List<String>> hMap, int index){
return (List<String>) hMap.values().toArray()[index];
}
你可能需要考虑使用另一个类来存储数据,或者编写一个扩展 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));
}
}
curr
的目的。 - HasenList<String> result = (List<String>) hMap.values().toArray()[position];
在标准的Java集合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();