Reputation:
I am using
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");
}
My output is :
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?
thanks.
Upvotes: 1
Views: 857
Reputation: 22972
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);
}
OUTPUT
Key : 1 - Value : cat
Key : 2 - Value : dog
Key : 3 - Value : car
Key : 1 - Value : cat
Key : 2 - Value : dog
Key : 2 - Value : dog
NOTE : Case sensitive, in above code it will consider that Dog
and dog
both are different.
Upvotes: 1
Reputation: 6079
You can try this code below:
Map<Integer, String> adi = new HashMap<>();
adi.put(0, "cat");
adi.put(1, "dog");
adi.put(2, "car");
adi.put(3, "car");
adi.put(4, "car");
adi.put(5, "PC");
int lastKey = 0;
String lasValue = "";
for (Map.Entry<Integer, String> entry : adi.entrySet()) {
if (!entry.getValue().equals(lasValue)) {
lastKey = entry.getKey();
}
lasValue = entry.getValue();
//tv.setText(tv.getText()+"Key : " + lastKey+ " Value : " + entry.getValue()+"\n");
System.out.println("Key : " + lastKey+ " Value : " + entry.getValue());
}
And this is the output:
Key : 0 Value : cat
Key : 1 Value : dog
Key : 2 Value : car
Key : 2 Value : car
Key : 2 Value : car
Key : 5 Value : PC
Upvotes: 0
Reputation: 10177
You would just make a second map, and as you iterate through the elements of the first map, flip the key-value to be the value-key of the second map. If first map's value has already been added to second map as a key, do not overwrite, and output the key-stored-as-a-value in the latter, otherwise output the new key.
Upvotes: 1