-5

Hi all :) I`ve got very easy problem I spend more than 2 hours searching here and on java docs. So I have a string which contain more than 5k lines in each line there are 6 numbers from 1-49 and they are separated by ";". I want to count how many times each of the number occur in my very long string. Most of topic which i found was about char counting. The closest i think was to use common lang and function .countMatches should I use arrayList? I need some clue, if solution is to long tip me how to do it :)

Biedek91
  • 1
  • 1

2 Answers2

1

the straightforward solution is to read line by line from your file and split by ;, then you got each number as string, finally put them into a HashMap<String, Integer>, if the key exists, just +1 the value. At the end you have the counts for each string (your number).

I hope I understand your question right.

Kent
  • 189,393
  • 32
  • 233
  • 301
0

Try this:

  1. Create a variable to hold the counts. Here is an example: Map<String, Integer> counts = new HashMap<String, Integer>();
  2. Split each line using String.split() (specifically line.split(";").
  3. Each time you split the line you will receive an array of numbers. for each of these numbers, retrieve the value from the the counts map. if null, add it to the map with a count of 1, of not null, increment the count and add it back to the map.

Edit: some code.

Map<String, Integer> counts = new HashMap<String, Integer>();
String line;
String[] parts

while (there are more lines)
{
    line = read the line somehow.
    parts = line.split(";");
    if (parts != null)
    {
        for (String current : parts)
        {
            Integer value = counts.get(current);
            if (value == null) // number not in the counts map yet.
            {
                counts.put(current, 1);
            }
            else
            {
                int currentCount = value.intValue() + 1;
                counts.put(current, currentCount);
            }
        }
    }
}
DwB
  • 37,124
  • 11
  • 56
  • 82