4

I'm trying to create a program that lets you put any data into a table and you can perform functions like count how many words there are in a column, row etc. Is using a HashMap the best way to go about this?

If not what can you recommend?

At the moment I'm struggling to count each of the letters and it's adding 1 to each of the values each time giving a = 8, b and c = 0

public  void main(String[] args){
    map.put("0", "a");
    map.put("1", "b");
    map.put("2", "c");
    map.put("3", "a");
    map.put("4", "b");
    map.put("5", "a");
    map.put("6", "b");
    map.put("7", "c");

    for(Map.Entry ent : map.entrySet()){
        if(map.containsValue("a")){
        x++;}

        else if(map.containsValue("b")){
        y++;}

        else if(map.containsValue("c")){
        z++;}
    }

    System.out.println("a = " + x);
    System.out.println("b = " + y);
    System.out.println("c = " + z);
0

2 Answers 2

1

Is using a HashMap the best way to go about this?

HashMap is a good way to go, but the way you are using it in your example is flawed because you can't simply count how many occurrences of a key are present.

So I suggest using HashMap<String, List<Integer>>, with List<Integer> keeping track of row indices:

    HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
    String[] strs = {"a", "b", "c", "a", "b", "a", "b", "c"};

    for(int i = 0 ; i < strs.length ; i++) {
        String s = strs[i];
        if(map.containsKey(s)) {
            map.get(s).add(i);
        } else {
            map.put(s, Arrays.asList(new Integer[]{i}));
        }
    }

    System.out.println("a = " + map.get("a").size());
    System.out.println("b = " + map.get("b").size());
    System.out.println("c = " + map.get("c").size());
Sign up to request clarification or add additional context in comments.

2 Comments

how to keep a number of a row?
@AndrewTobilko Instead of Integer, you could use List<Integer> for indices of rows, and list.size() would be the number of occurences
0

In case you are okay with using a data structure from a third party, you may want to use Guava's ArrayListMultimap:

Multimap<Character, Integer> map = ArrayListMultimap.create();
String str = "abcababc";

for (int i = 0 ; i < str.length() ; i++) {
    map.put(str.charAt(i), i);
}

for (Character c : map.keySet()) {
    System.out.println(String.format(%c = %d", c, map.get(c).size());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.