Search code examples
javacollectionstreemap

User-defined class objects in Java TreeMap


I have a collection (TreeMap), I want to print only one value from the Object im passing. Here is the code that I have being trying

Student.java

    class Student {
        int rollno;
        String name;
        int age;
        Student(int rollno,String name,int age){
            this.rollno=rollno;
            this.name=name;
            this.age=age;
         }

         public String toString(){//overriding the toString() method
             return rollno+" "+name+" "+age;
         }

     }

StudentTest.java

 import java.util.*;
 import java.io.*;
 class StudentTest{
     public static void main(String args[]){

         Map<String,Student> al=new TreeMap<String,Student>();
         al.put("a1",new Student(101,"Vijay",23));
         al.put("a2",new Student(106,"Ajay",27));
         al.put("a3",new Student(105,"Jai",21));


         Set set = al.entrySet();
         // Get an iterator
         Iterator i = set.iterator();

         // Display elements
         while(i.hasNext()) {
             Map.Entry me = (Map.Entry)i.next();
             System.out.print(me.getKey() + ": ");
             System.out.println(me.getValue());
         }


         System.out.println(al.get("a1"));

         System.out.println(al.size());

         Set<String> keys =al.keySet();
         for(String key : keys)
             {
                 System.out.println(al.get(key));

             }

        Collection entrySet = al.entrySet();
        Iterator<Student> itr = entrySet.iterator();
        System.out.println("+++++++"+entrySet);
        System.out.println("\n\n\n\n\n");
        System.out.println("+++++++"+itr);
        System.out.println("\n\n\n\n\n");
        while(itr.hasNext())
        {
           Student  st = itr.next();
            System.out.println(st.rollno);
        }
    }
}
  1. I want to print only one value that is either rollno or name or age

  2. Also I want to print name as Vijay that is only one name from the collection

Please let me know the solution for the error im getting for the code Im trying .


Solution

  • The entrySet of a map is a set of Map.Entry<KeyType, ValueType>s.

    You have this:

    Collection entrySet = al.entrySet();
    Iterator<Student> itr = entrySet.iterator();
    

    If you weren't using a raw type in the first line, the error would be much more obvious. Never use raw types:

    Collection<Student> entrySet = al.entrySet(); // ERROR HERE - Set<Map.Entry<String, Student>> cannot be cast to Collection<Student>
    Iterator<Student> itr = entrySet.iterator();
    

    If you want to iterate over the values in your map, use values:

    Collection<Student> entrySet = al.values();
    Iterator<Student> itr = entrySet.iterator();