[英]Get key from HashMap in Android by position or index
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
.我试图从
CHILD_NAME_DOB
获取最后一个关键元素。 That is, I want to fetch key alisha
from the example above to temporary String name
.也就是说,我想从上面的示例中获取密钥
alisha
到临时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
,我想要String name
键"Neha"
TIA. TIA。
Edit: DateOfBirth value (value data in CHILD_NAME_DOB
) is dynamic and is unknown.编辑:DATEOFBIRTH值(值数据
CHILD_NAME_DOB
)是动态的,是未知的。 So THIS LINK is not what I want.所以这个链接不是我想要的。
Single line solution:单线解决方案:
First note that the Java HashMap
does not guarantee the order of entries.首先请注意,Java
HashMap
不保证条目的顺序。 So each time you iterate over a HashMap, entries appear in different positions.因此,每次迭代 HashMap 时,条目都会出现在不同的位置。 You will need
LinkedHashMap
that guarantees the predictable iteration order.您将需要
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)
Thanks to @Pentium10 for this answer.感谢@Pentium10 的回答。 And I little modified it according to my need.
我根据我的需要稍微修改了它。
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.我会尽快更新,我也会找到一种简单的按索引键的方法。
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;
}
You can also use an ArrayMap instead of a HashMap.您还可以使用 ArrayMap 而不是 HashMap。 To get the value by index use:
要按索引获取值,请使用:
ArrayMap.valueAt(index);
To get the Key at an index use:要在索引处获取密钥,请使用:
ArrayMap.keyAt(index);
Fetching the "last" key and fetch by index is not supported by HashMap
. HashMap
不支持获取“最后一个”键和按索引获取。 You can use a LinkedHashMap
and lookup the element with index 2 (or the last element) by iterating over it.您可以使用
LinkedHashMap
并通过迭代查找索引为 2(或最后一个元素)的元素。 But this will be a O(n) operation.但这将是一个 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>>
我建议您使用List<Pair<String, String>>
。
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)
.如果基于键和基于索引的查找对您都很重要,您可以使用由
List
和HashMap
组成的组合数据结构,但请注意,删除元素将是O(n)
。
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>
(作为 Child 对象)
HashMap
does not have a concept of ordering, so getting the n-th entry does not make sense. HashMap
没有排序的概念,所以获取第 n 个条目没有意义。 You could use a TreeMap
instead, which is ordered on its keys.您可以改用
TreeMap
,它是按其键排序的。
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
.一方面,按索引访问是典型的
Lists
,而按键访问是典型的Maps
。 I'm not sure in which situation you'd want to do both.我不确定在哪种情况下你想同时做这两种事情。
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.
我不建议这样做,但如果这真的是你想要的,那么我认为这是最好的解决方案。
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.如果删除条目,您可能会遇到一些问题,但这应该只是一个建议。
for (String key : hmList.keySet()) {
String value = hmList.get(key);
Log.e("HashMap values", "key=" + key + " ,value=" + value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.