Java List Question

I have such a program

public class no_of_letters_count { static int i; public static void main(String[] args) { String sMessage="hello how ru"; String saMessage[] = sMessage.split(""); List sList = Arrays.asList(saMessage); Collections.sort(sList); Iterator i=sList.iterator(); while (i.hasNext()) { System.out.println((String)i.next()); } } } //Now i want to count the number of occurance of each characters. 

how

The number h = 2

The number e = 1

etc.

+4
source share
4 answers

sList over sList and put each char in a HashMap . If it does not exist, start with count 1 , otherwise increase the counter.

EDIT: Unable to publish code.

First of all, use gnerics.

 List<Character> sList = Arrays.asList(saMessage.toCharArray()); 

Then use the following card:

 Map<Character, Integer> cmap = new HashMap<Character, Integer>(); 
+4
source

Using collection collections and commons-lang

 List<Character> chars = Arrays.asList( ArrayUtils.toObject("asdfasdas".toCharArray())); Bag bag = new HashBag(chars); System.out.println(bag.getCount('a')); 
+1
source

Here are some suggestions:

It seems you are just trying to get characters in a String . Use String.toCharArray() .

Use Map<Character,Integer> to store characters and their appearance:

 foreach char c in sMessage.ToCharArray() if map.containsKey(c) map.put(c, map.get(c) + 1); else map.put(c, 1); 

Then collect the map and present the results. I leave you a fragment for sorting 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()); } }); 
0
source

Prints the number of occurrences of characters from AZ and az

Note : using a character as an index of an array is not safe if you have Unicode characters :), but still a 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]); } 
0
source

Source: https://habr.com/ru/post/1299943/


All Articles