using the FOR loop to catch multiples of the same number
I have a String that holds the value of an ID number from a query that I am parsing into an Integer. I need a FOR loop that checks every time a certain n开发者_C百科umber appears in the query more than five times. I am displaying this information on a JSP page. So far I have:
while (rs1.next()){
String TicketNumber = rs1.getString("XXXXX_XXXXX_NO");
String MUID = rs1.getString("XXXXXX_XXXX");
String Name = rs1.getString("XXXXXXX_XXXXX_NAME");
String LastName = rs1.getString("XXXXX_XXXX_NAME");
int PIDM = Integer.parseInt(MUID);
for ( int n = 0, n >= 5, n += 1 )
rs1 is the statement that I am quering and I am setting these values, parsing out the MIUD into PIDM but I am not quite sure where to go from there.
Just make use of the powerful aggregate functions the SQL offers you on that area:
SELECT muid, COUNT(muid) AS muid_count FROM ticket GROUP BY muid
in combination with
Integer muid = resultSet.getInt("muid");
Integer muidCount = resultSet.getInt("muid_count");
Or if you're actually interested in the non-aggregated information, then best is indeed to use a Map<Integer, Integer>
or maybe better Map<Integer, List<Ticket>>
so that you can just display it in JSP at once nicely using JSTL c:forEach
. You can then get the size of List<Ticket>
using JSTL fn:length
.
E.g.
<c:forEach items="${ticketMap}" var="ticketEntry">
MUID: ${ticketEntry.key}<br>
Ticket count: ${fn:length(ticketEntry.value)}<br>
All tickets:<br>
<c:forEach items="${ticketEntry.value}" var="ticket">
Number: ${ticket.number}<br>
Name: ${ticket.name}<br>
Lastname: ${ticket.lastName}<br>
</c:forEach>
<hr>
</c:forEach>
Use a Map to count the number of times each number appears.
Map<Integer,Integer> map = new HashMap<Integer,Integer>()
Do this for every record in the result set
Integer count = map.get(PIDM);
if( count == null )
map.put(PIDM, 1);
else
map.put(PIDM, count + 1);
Then, after the query is done, loop through looking for a count of 5 or greater
for( Map.Entry<Integer,Integer> e : map.entrySet() )
{
if( e.getValue() > 5 )
{
// do something with e.getKey() which is the PIDM from above
}
}
精彩评论