Monday, 14 September 2015

TreeMap Class Example 2

import java.util.*;
class Student
{ int rollno;
String name;
String phone;
}
class Comp implements Comparator<Student>
{ public int compare(Student s1, Student s2)
{ int c;
if(s1.rollno < s2.rollno)
c = -1;
else if (s1.rollno > s2.rollno)
c = 1;
else
c = 0;
return c;
}
}

class TreeMapDemo1
{ public static void main(String args[])
{   TreeMap<Student,Double> tm=new TreeMap<Student,Double>(new Comp());
// Add elements to the tree set.
Student s1 = new Student();
s1.rollno = 1; s1.name = "Rahul"; s1.phone = "2590381";

Student s2 = new Student();
s2.rollno = 5; s2.name = "Devesh"; s2.phone = "9829059033";

Student s3 = new Student();
s3.rollno = 3; s3.name = "Rakesh"; s3.phone = "2590381";

Student s4 = new Student();
s4.rollno = 2; s4.name = "Manohar"; s4.phone = "2590381";

Student s5 = new Student();
s5.rollno = 4; s5.name = "Prateek"; s5.phone = "2590381";

tm.put(s1, 1000.0);
tm.put(s2, 2000.0);
tm.put(s3, 3000.0);
tm.put(s4, 4000.0);
tm.put(s5, 5000.0);

Set<Student> set = tm.keySet();
for(Student s : set)
{
System.out.print(s.rollno + ", " + s.name + ", " + s.phone
+ "; " + "balance:");
System.out.println(tm.get(s));
  }
}
}

No comments:

Post a Comment