It looks like you need a custom data type to encapsulate each row rather than using a String[][]
, but to answer your question more directly, you can use a Map<String,Integer>
for each column. A HashMap<String,Integer>
can be expected to do this in optimal time.
Here's a snippet to demonstrate the idea:
import java.util.*;
public class Frequency {
static void increment(Map<String,Integer> map, String key) {
Integer count = map.get(key);
map.put(key, (count == null ? 0 : count) + 1);
}
public static void main(String[] args) {
String table[][] = new String[][] {
{"127.0.0.9", "60", "75000","UDP", "Good"},
{"127.0.0.8", "75", "75000","TCP", "Bad"},
{"127.0.0.9", "75", "70000","UDP", "Good"},
{"127.0.0.1", "", "70000","UDP", "Good"},
{"127.0.0.1", "75", "75000","TCP", "Bad"}
};
final int M = table.length;
final int N = table[0].length;
List<Map<String,Integer>> maps = new ArrayList<Map<String,Integer>>();
for (int i = 0; i < N; i++) {
maps.add(new HashMap<String,Integer>());
}
for (String[] row : table) {
for (int i = 0; i < N; i++) {
increment(maps.get(i), row[i]);
}
}
for (Map<String,Integer> map : maps) {
System.out.println(map);
}
System.out.println(maps.get(0).get("127.0.0.9"));
}
}
This produces the following output: each line is a frequency map for each column:
{127.0.0.9=2, 127.0.0.8=1, 127.0.0.1=2}
{=1, 60=1, 75=3}
{75000=3, 70000=2}
{UDP=3, TCP=2}
{Good=3, Bad=2}
2
Note: if you don't care about mixing values from all columns together, then you only need one Map
, instead of a List<Map>
one for each column. This would make the design even worse, though. You really should encapsulate each row into a custom type, instead of a having everything mixed as String[][]
.
For example some of those columns really looks like they should be an enum
.
enum Protocol { UDP, TCP; }
enum Condition { Good, Bad; }
//...