Below is the code to retrieve the key from HashMap using value
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class TestClass {
public static void main(String[] args) {
Map<Integer, Person> people = new HashMap<Integer, Person>();
Person person1 = new Person();
person1.setName("Mack");
person1.setPost("Dev");
Person person2 = new Person();
person2.setName("John");
person2.setPost("Dev");
people.put(1, person1);
people.put(2, person2);
Set<Entry<Integer, Person>> peopleSet = people.entrySet();
for (Entry<Integer, Person> entry : peopleSet) {
Integer key = entry.getKey();
Person value = entry.getValue();
if (value.equals(person2)) {
System.out.println("Key = " + key);
}
}
}
}
No comments:
Post a Comment