比较的Hashmap字符串值,然后重复与重复输入键 [英] Compare Hashmap String value and duplicate key for Repeated entry
问题描述
我使用
Map<Integer, String> adi = new HashMap<Integer, String>();
for(int u=0; u< sari_nodes.size();u++){
adi.put(u, sari_nodes.get(u));
}
for (Map.Entry<Integer, String> entry : adi.entrySet()) {
tv.setText(tv.getText()+"Key : " + entry.getKey()+ " Value : " + entry.getValue()+"\n");
}
我的输出是:
key: 0 Value : cat
key: 1 Value : dog
key: 2 Value : car
key: 3 Value : car
key: 4 Value : car
key: 5 Value : car
我要重复的密钥相同的条目,所以我的输出看起来像
I want to repeat the key for same entry so that my output looks like
key: 0 Value : cat
key: 1 Value : dog
key: 2 Value : car
key: 2 Value : car
key: 2 Value : car
key: 2 Value : car
我怎样才能进行检查,以得到这些类型的重复键?
How can I perform a check to get these kind of repeated keys?
有人可以给我一些指导解决这个问题?
Can somebody give me some guidance on solving this issue?
感谢。
推荐答案
我第二 的答案名称空间
。
您希望每个值是唯一的。因此,您可以创建一个地图,添加当前地图的价值作为重点。最终,我们正试图获取了相同的值相同的密钥(第一密钥)。你可以做到这一点的方法如下:
You want every value to be unique. So, for that you can create a map which add value of your current map as a key. Ultimately we are trying to fetch the same key (first key) for same values. You can do it in a following way.
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "cat");
map.put(2, "dog");
map.put(3, "car");
map.put(4, "cat");
map.put(5, "dog");
map.put(6, "dog");
Map<String, Integer> uniqueValues = new HashMap<>();
for (Entry<Integer, String> entry : map.entrySet()) {
Integer key = entry.getKey();
String val = entry.getValue();
if (uniqueValues.containsKey(val)) {
key = uniqueValues.get(val);
}
uniqueValues.put(val, key);
System.out.println("Key : " + key + " - Value : " + val);
}
输出
Key : 1 - Value : cat
Key : 2 - Value : dog
Key : 3 - Value : car
Key : 1 - Value : cat
Key : 2 - Value : dog
Key : 2 - Value : dog
的注:的大小写,在上面code它会认为狗
和狗
这两个是不同的。
NOTE : Case sensitive, in above code it will consider that Dog
and dog
both are different.
这篇关于比较的Hashmap字符串值,然后重复与重复输入键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!