1

i want to store name and id of HQL query result into a Hashmap . here is my code. is there any better way to do it?

    String hql = "FROM Student";
    Session session = HibernateUtil.getSessionFactory().openSession();
    Query query = session.createQuery(hql);
    List queryResults = query.list();
    List<Student> result = new ArrayList<Student>();

    Iterator it = queryResults.iterator();
    while (it.hasNext()) {
        Student student = (Student) it.next();
        result.add(student);
    }
    Map mapresult = new LinkedHashMap<Integer,String>();

    for (Student Maprslt : result)
        mapresult.put(Maprslt.getId(), Maprslt.getName());
0

1 Answer 1

3

You could put it all in a single foreach loop, which is designed to loop over an Iterable or array.

String hql = "FROM Student";
Session session = HibernateUtil.getSessionFactory().openSession();
Query query = session.createQuery(hql);
List queryResults = query.list();

Map<Integer,String> mapresult = new LinkedHashMap<>();
for (Object obj : queryResults) {
    Student student = (Student) obj;
    mapresult.put(student.getId(), student.getName());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.