比较 Hashmap 字符串值和重复项的重复键 [英] Compare Hashmap String value and duplicate key for Repeated entry

查看:28
本文介绍了比较 Hashmap 字符串值和重复项的重复键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

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?

谢谢.

推荐答案

我第二次回答NameSpace.

I second the answer of NameSpace.

您希望每个值都是唯一的.因此,为此您可以创建一个地图,将当前地图的值添加为键.最终,我们试图为相同的值获取相同的键(第一个键).您可以通过以下方式进行.

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

注意:区分大小写,在上面的代码中会认为Dogdog是不同的.

NOTE : Case sensitive, in above code it will consider that Dog and dog both are different.

这篇关于比较 Hashmap 字符串值和重复项的重复键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆