Java Tutorial Series - collections - Using Custom Objects in Sets and as Keys in Maps

By this tutorial you know already know the concepts of collections framework in Java - ArrayList, LinkedList, HashMap, LinkedHashMap, TreeHashMap, HashSet, LinkedHashSet, TreeSet. Now we will learn how to using custom objects in Sets and keys in maps.

Please consider below piece of code for reference -

Using Custom Objects in Sets and Keys in Maps - 

public class Person {
private int id;
private String name;
Person(int id, String name) {
this.id= id;
this.name = name;
}
public String toString() {
return(" ïd : " + id + "Name :" + name );
}
}





public class App {
               public static void main(String[] Args) {

Person p1 = new Person(0,"Bob");
Person p2 = new Person(1,"Sue");
Person p3 = new Person(2,"Mike");
Person p4 = new Person(3,"Sue");

Map< Person,Integer> map = new HashMap< Person, Integer>();

map.put(p1, 1);
map.put(p2,2);
map.put(p3,3);
map.put(p4,1);

for(Person key: map.keySet()) {
    System.out.println(key + ":"+ map.get(key));


Set<Person> set1 = new HashSet<Person>();
set1.add(p1);
set1.add(p2);
set1.add(p3);
set1.add(p4);

System.out.println(set1);

}

}

If you will run above code the you wouldn't really find the functionality of map and Set work as it should, both of them would return duplicate values. To get the unique values and keys, we need to right click -> Source -> Generate hashCode() and equals() -> select the instance variables and click on Ok. You would be able to see the unique values for both Set and Map.

That's it! Hope you understood this article, Happy Learning and Happy Sharing! 

Comments

Popular posts from this blog

Azure Tutorials Series - Azure Networking

Coforge Interview Questions | Automation Testing profile

Testing in CI/CD