Java List question
I have a program like this
public class no_of_letters_count {
static int i;
public static void main(String[] args)
{
String sMessage="hello how r u";
String saMessage[] = sMessage.split("");
List sList = Arrays.asList(saMessage);
Collections.sort(sList);
Iterator i=sLis开发者_运维技巧t.iterator();
while (i.hasNext())
{
System.out.println((String)i.next());
}
}
}
//Now i want to count the number of occurance of each characters.
Like
Count of h=2
Count of e=1
and so on
Iterate over sList
and put each char
in a HashMap
. If it doesn't exists start with count 1
, otherwise increment the count.
EDIT : Cannot help posting some code.
First of all, use gnerics.
List<Character> sList = Arrays.asList(saMessage.toCharArray());
Then use the following map :
Map<Character, Integer> cmap = new HashMap<Character, Integer>();
Using commons-collections and commons-lang
List<Character> chars = Arrays.asList(
ArrayUtils.toObject("asdfasdas".toCharArray()));
Bag bag = new HashBag(chars);
System.out.println(bag.getCount('a'));
Prints number of occurrences of characters from A-Z and a-z
Note: using the character as array index, not safe if you have Unicode chars :), but still good idea i think!!
String str = "sometext anything";
int[] array=new int[256];
for (int x:array) array[x]=0;
for (char c:str.toCharArray()){
array[c]++;
}
for (int i=65;i<=90; i++){
System.out.println("Number of "+(char)i+ "="+array[i]
+ ", number of "+(char)(i+32)+"="+ array[i+32]);
}
Here are some hints:
It seems you are just trying to get the chars in a String
. Use String.toCharArray()
.
Use a Map<Character,Integer>
to store the chars and it's occurrences:
foreach char c in sMessage.ToCharArray()
if map.containsKey(c)
map.put(c, map.get(c) + 1);
else
map.put(c, 1);
Next sort the map and present the results. I leave you here a snippet to sort the map:
List<Entry<Character,Integer>> l = new ArrayList<Entry<Character,Integer>>(map.entrySet());
Collections.sort(l, new Comparator<Entry<Character,Integer>>() {
public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
精彩评论