Open In App

Printing TreeMap Having Custom Class Objects as Keys or Values in Java

Improve
Improve
Like Article
Like
Save
Share
Report

TreeMap is a map implementation that keeps its entry sorted according to the natural ordering of its keys. So, for an integer, this would mean ascending order, and for string, it would be alphabetical order. TreeMap can also be sorted according to the user by using a comparator at construction time.

Here we are going to see how to print TreeMap having custom class objects as keys or values. But before that, let’s see exactly what happens when trying to print it normally. While trying to print object directly printed value might not be in proper format and in multiple cases garbage values like  @agc1243 print at the output.

Normal Printing implementation:

Java




// Printing TreeMap Having Custom Class Objects directly
import java.io.*;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
  
// make a class Student
class Student {
  
    private Integer regId;
    private String name;
  
    public Student(Integer regId, String name)
    {
        this.regId = regId;
        this.name = name;
    }
  
    public Integer getId() { return regId; }
  
    public String getName() { return name; }
}
class GFG {
    public static void main(String[] args)
    {
  
        // creating a TreeMap
        TreeMap<Integer, Student> tmap
            = new TreeMap<Integer, Student>();
  
        // Mapping student objects to int keys
        tmap.put(1, new Student(101, "Abhay"));
        tmap.put(2, new Student(102, "Sarika"));
        tmap.put(3, new Student(103, "Vanshika"));
  
        // get all entries
        Set<Map.Entry<Integer, Student> > entries
            = tmap.entrySet();
  
        // printing keys and values using for loop
        for (Map.Entry<Integer, Student> entry : entries) {
            System.out.println(entry.getKey() + "=>"
                               + entry.getValue());
        }
    }
}


Output

1=>Student@3941a79c
2=>Student@506e1b77
3=>Student@4fca772d

 

The reason why the output is not in the proper format?

The reason is our Student class has not overridden the toString method from the Object class. So that is why the toString method of the Object class is used here which prints “class_name@object_hashcode” when an object is printed.

So, the next question is How to fix this?

To fix this, override the toString method in our Student class.

Implementation:

Java




// Printing TreeMap Having Custom Class
// Objects as Keys or Values in Java
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
  
// make a class Student
class Student {
  
    private Integer regId;
    private String name;
  
    public Student(Integer regId, String name)
    {
        this.regId = regId;
        this.name = name;
    }
  
    public Integer getId() { return regId; }
  
    public String getName() { return name; }
    /*
     * Override this method in your custom class
     * used as key or value in the TreeMap
     */
    public String toString()
    {
        return "[" + this.getId() + "=>" + this.getName()
            + "]";
    }
}
class GFG {
    public static void main(String[] args)
    {
  
        // creating a TreeMap
        TreeMap<Integer, Student> tmap
            = new TreeMap<Integer, Student>();
  
        // Mapping student objects to int keys
        tmap.put(1, new Student(101, "Abhay"));
        tmap.put(2, new Student(102, "Sarika"));
        tmap.put(3, new Student(103, "Vanshika"));
  
        // get all entries
        Set<Map.Entry<Integer, Student> > entries
            = tmap.entrySet();
  
        // printing keys and values using for loop
        for (Map.Entry<Integer, Student> entry : entries) {
            System.out.println(entry.getKey() + "=>"
                               + entry.getValue());
        }
    }
}


Output

1=>[101=>Abhay]
2=>[102=>Sarika]
3=>[103=>Vanshika]

Note: So the main tip here to remember is to always override the toString() method in your custom classes.



Last Updated : 04 Jan, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads