public class Student{ private String name; private int studentId; //getter and setters } Write a method which accepts a Set of Student objects and returns a Map with Student Id as key and name as value.
Here comes an example that stores the student object into Set and display the data in the form of key value pair.
import java.util.*; public class Student{ public static Map displayData(){ Set<Student> set=new HashSet<Student>(); Scanner input=new Scanner(System.in); for(int i=1;i<=5;i++){ System.out.print("Enter ID: "); int id=input.nextInt(); System.out.print("Enter Name: "); String name=input.next(); set.add(new Student(id,name)); } HashMap<Integer,String> map=new HashMap<Integer,String>(); for(Student st:set){ map.put(st.getStudentId(),st.getName()); } return map; } private String name; private int studentId; Student(int studentId,String name){ this.studentId=studentId; this.name=name; } public void setName(String name){ this.name=name; } public String getName(){ return name; } public void setStudentId(int studentId){ this.studentId=studentId; } public int getStudentId(){ return studentId; } public static void main(String []args){ Map map=displayData(); Set set = map.entrySet(); Iterator i = set.iterator(); while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } } }
Ads