Please help me to solve this problem. The problem is that I have a table which stores the all kind of alarms now I need to know count of one particular alarms. for example
alarms
---------
aaa
aaa
aaa
ccc
ccc
aaa
bbb
bbb
as shown in the above table I have to count how many times say (aaa) has repeated in this case its is 4 similarly for bbb in this case it is 2 and for ccc it is 2.
How to solve this problem?
Something like this:
Hashtable<String, Integer> hash = new Hashtable<String, Integer>();
for (String alarm : alarms) {
Integer count = hash.get(alarm);
if (count == null) count = 1;
else count++;
hash.put(alarm, count);
}
I'm not sure your use of the word table indicates a database table, but I'm thinking it does. If that's the case, I'd suggest writing SQL that will just get the number of occurrences directly from the table.
select count(*) from table where alarms = 'aaa';
Alternatively, if you'll have to do this for each alarm type, you could do a query like:
select alarms, count(alarms) from table group by alarms;
And from there you could store it in a HashMap<String, Integer>
as others have said. Of course, if you didn't mean a database table, then feel free to ignore this answer. =)
Try to iterate over that alarm list. Use a HashMap that holds alarm name and count. When you get an alarm check it on HashMap, if exists increase the count otherwise put it into that HashMap and set count as 1, repeat until the end. When you iterate over that HashMap you will able to see which ones has alarmed and how many times.
Can you give a little bit more information on how is the data actually stored?
If it is stored exactly as you mentioned here, that is as a string separated by spaces, then, you can do something like this:
String alarms = "aaa aaa aaa ccc ccc aaa bbb bbb";
String[] alarmCounter = alarms.split(" ");
for (String str : alarmCounter)
{
System.out.println("There are " + str.length + " alarms of type " + str.charAt(0));
}
精彩评论