java 通过位置或索引从Android中的HashMap获取键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28981797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get key from HashMap in Android by position or index
提问by DancingMonkeyOnLaughingBuffalo
I have:
我有:
public static HashMap<String, String> CHILD_NAME_DOB = new HashMap<>();
Suppose the values in CHILD_NAME_DOB
are:
假设 中的值CHILD_NAME_DOB
是:
<adam,15121990>
<roy,01051995>
<neha,05091992>
<alisha,11051992>
I am trying to fetch the last key element from CHILD_NAME_DOB
. That is, I want to fetch key alisha
from the example above to temporary String name
.
我正在尝试从CHILD_NAME_DOB
. 也就是说,我想alisha
从上面的例子中获取 key到 temp String name
。
Also I want to know on how to fetch data by index.
另外我想知道如何通过索引获取数据。
Eg.: if int index = 2
, I want key "Neha"
in String name
例如:如果int index = 2
,我想关键"Neha"
在String name
TIA.
TIA。
Edit: DateOfBirth value (value data in CHILD_NAME_DOB
) is dynamic and is unknown. So THIS LINKis not what I want.
编辑:DateOfBirth 值(中的值数据CHILD_NAME_DOB
)是动态的并且是未知的。所以这个链接不是我想要的。
采纳答案by DancingMonkeyOnLaughingBuffalo
Thanks to @Pentium10 for this answer.And I little modified it according to my need.
感谢@Pentium10 的回答。我根据我的需要修改了它。
String key="default";
Iterator myVeryOwnIterator = CHILD_NAME_DOB.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
key=(String)myVeryOwnIterator.next();
//String value=(String)meMap.get(key);
}
Toast.makeText(viewEnterChildExp.getContext(), "Key: "+key , Toast.LENGTH_LONG).show();
I'm getting the last key element by this.
我得到了最后一个关键元素。
I'll update as soon I also get to find an easy way to key by index.
我会尽快更新,我也会找到一种按索引键的简单方法。
回答by abedfar
Single line solution:
单线解决方案:
First note that the Java HashMap
does not guarantee the order of entries. So each time you iterate over a HashMap, entries appear in different positions. You will need LinkedHashMap
that guarantees the predictable iteration order.
首先请注意,JavaHashMap
不保证条目的顺序。因此,每次迭代 HashMap 时,条目都会出现在不同的位置。您将需要LinkedHashMap
保证可预测的迭代顺序。
Map<String, String> CHILD_NAME_DOB = new LinkedHashMap<>();
Get the key by index:
通过索引获取key:
key = (new ArrayList<>(CHILD_NAME_DOB.keySet())).get(index)
Get the value by index:
通过索引获取值:
CHILD_NAME_DOB.get(key)
回答by vishwajit76
This way to get key....
这样才能拿到钥匙....
public static String getHashMapKeyFromIndex(HashMap hashMap, int index){
String key = null;
HashMap <String,Object> hs = hashMap;
int pos=0;
for(Map.Entry<String, Object> entry : hs.entrySet())
{
if(index==pos){
key=entry.getKey();
}
pos++;
}
return key;
}
回答by aioobe
Fetching the "last" key and fetch by index is not supported by HashMap
. You can use a LinkedHashMap
and lookup the element with index 2 (or the last element) by iterating over it. But this will be a O(n) operation.
不支持获取“最后一个”键和按索引获取HashMap
。您可以使用 aLinkedHashMap
并通过迭代查找索引为 2(或最后一个元素)的元素。但这将是一个 O(n) 操作。
I suggest you use a List<Pair<String, String>>
if the order of the keys/values is important to you and you wish to do index based lookup.
List<Pair<String, String>>
如果键/值的顺序对您很重要并且您希望进行基于索引的查找,我建议您使用 a 。
If both key based and index based lookup is important to you, you could use a combined data structure that consists of both a List
and a HashMap
, but note that removal of elements will be O(n)
.
如果基于键和基于索引的查找对您都很重要,您可以使用由 aList
和 a组成的组合数据结构HashMap
,但请注意,元素的删除将是O(n)
。
回答by Fabrizio Morello
You can create a class Child
您可以创建一个类 Child
public class Child(){
private String name;
private String number;
....
}
and then put this object in a List
然后把这个对象放在一个列表中
public static List<Child> CHILD_NAME_DOB = new ArrayList<Child>(); // using LinkedList would defeat the purpose
in this way you can invoke the method get(int index)
, that returns the element at the specified position in this list.
通过这种方式,您可以调用get(int index)
返回此列表中指定位置的元素的方法。
In your example
在你的例子中
<adam,15121990>
<roy,01051995>
<neha,05091992>
<alisha,11051992>
invoking CHILD_NAME_DOB.get(2)
you'll get <neha,05091992>
(as Child object)
调用CHILD_NAME_DOB.get(2)
你会得到<neha,05091992>
(作为子对象)
回答by velval
You can also use an ArrayMap instead of a HashMap. To get the value by index use:
您还可以使用 ArrayMap 而不是 HashMap。要按索引获取值,请使用:
ArrayMap.valueAt(index);
To get the Key at an index use:
要在索引处获取密钥,请使用:
ArrayMap.keyAt(index);
回答by Warkst
HashMap
does not have a concept of ordering, so getting the n-th entry does not make sense. You could use a TreeMap
instead, which is ordered on its keys.
HashMap
没有排序的概念,因此获取第 n 个条目没有意义。您可以使用 aTreeMap
代替,它在其键上排序。
However, you should reconsider your model as you seem to have conflicting interests. On the one hand, accessing by index is typical for Lists
, whereas accessing by key is typical for Maps
. I'm not sure in which situation you'd want to do both.
但是,您应该重新考虑您的模型,因为您似乎有利益冲突。一方面,按索引访问是典型的Lists
,而按键访问是典型的Maps
。我不确定在哪种情况下你想同时做这两种事情。
If you really want to do both index and key accessing, you could write your own data structure that stores the data in a list combined with a mapping from key to index and vice versa. I would recommend against this, but if that's really what you want, then I think that's the best solution.
如果您真的想同时进行索引和键访问,您可以编写自己的数据结构,将数据存储在列表中,并结合从键到索引的映射,反之亦然。我不建议这样做,但如果这真的是你想要的,那么我认为这是最好的解决方案。
回答by dieter
I know it is not the best solution, but what about this solution (pseudocode!). Just combine List and Map in one class.
我知道这不是最好的解决方案,但是这个解决方案怎么样(伪代码!)。只需将 List 和 Map 组合在一个类中。
public class UserBirthday {
private List<String> names = new ArrayList<>();
private Map<String, String> CHILD_NAME_DOB = new HashMap<String, String>();
public void add(String name, String bd) {
if (!CHILD_NAME_DOB.containsKey(name)) {
names.add(name);
}
CHILD_NAME_DOB.put(name, bd);
}
public String getByName(String name) {
return CHILD_NAME_DOB.get(name);
}
public String getByIndex(int index) {
return getByName(names.get(index)); // TODO: range test
}
public static void main(String[] args) {
UserBirthday ub = new UserBirthday();
ub.add("dit", "12345678");
ub.add("lea", "234239423");
ub.add("alex", "43534534");
ub.add("ted", "099098790");
System.out.println(ub.getByIndex(2));
System.out.println(ub.getByName("alex"));
}
}
You may get some problems if you remove an entry, but it should be just a suggestion.
如果删除条目,您可能会遇到一些问题,但这应该只是一个建议。
回答by Atif Mahmood
for (String key : hmList.keySet()) {
String value = hmList.get(key);
Log.e("HashMap values", "key=" + key + " ,value=" + value);
}