hi im new to java and jst practicing it.....
I have used hashmap to retrieve the data from data base....
here after retrieving them to a table i want to get only one record from that hashmap table and display below.....
please can any one help.....
Mohamed Sanaulla wrote:Please UseRealWords - im, jst are not understood by all.
I thought he was new to Java and Jstl
First of all HashMap is a key-value based collection and can be accessed by using the Keys and not by index of the entry.
Now in your case the key is "id". I am not sure what this id signifies but if it is the kind of rowid which goes sequentially like 1,2,3,4,5 etc then you have a chance to get the 5th record by calling hm.get(5).
If your key which is "id" is not somehthing like rowid then you need to iterate the HashMap and reach 5th entry. This might return you different results everytime you iterate the hashmap because
1) The query you are firing may not return the results in the same order everytime
2) A simple Iterator does not guarantee iteration order.
Iterator<E> iterator() - Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).
You can do something like this -
1) Change your query to add ORDER BY Clause so that you get ordered resultset.
2) Secondly while iterating through the resultset and adding it to the HashMap, maintain a counter. Use this counter as the Key in the HashMap. This will help you to get the nth record directly using key-based lookup.
anusha sivakumar wrote:
Off-topic, but that's going to bite you in the behind sometime in the future. If somebody adds a column to your table between two other columns the indexes will change. Either specify which columns you retrieve in the select statement (select id, date, time, ... from appointments) or retrieve them using their name (rs.getString("id") etc).