0

Given a 2D Array, count the number data at column 3 where it is the same.

For example,

 String[][] array = {
                    { "red", "value1", "alpha"  },
                    { "blue", "value2", "alpha"  }, 
                    { "green", "value3", "alpha"  }, 
                    { "black", "value4", "alpha" },
                    { "grey", "value1", "beta"  },
                    { "white", "value2", "beta"  }, 
            };

          int counter=0;
          for(String[] subArray : array)
              for(String string : subArray)
                  if(string.toLowerCase().equals("beta"))
                      counter++;

          System.out.println(counter); 

The output of the counter for beta = 2 and alpha = 4.

Assuming I don't know what is the exact name of the data in column 3, how I count the conditions? if(string.toLowerCase().equals(???))

Any help will be appreciated!

3 Answers 3

2

It could be something like this using groupingBy in java 8:

 Arrays.stream(array)
       .collect(Collectors.groupingBy(arr -> arr[2], Collectors.counting()));

Result will:

{alpha=4, beta=2}

B.T.W If you want to ignore case, do it as:

Arrays.stream(array)
      .collect(Collectors.groupingBy(arr -> arr[2].toLowerCase(), Collectors.counting()));
Sign up to request clarification or add additional context in comments.

Comments

1

Create a Map<String, int>

Look for the value of string.toLowerCase in the Map and if it is found increment the value of int else insert with the value of 1

Comments

0

There are many ways, but one way:

  1. Create a new multidimensional array of types string:int.

  2. Iteratethrough your array at the last index, and then check if it exists in your array you made.

  3. If it exists, inremement the int to int+1.
  4. If it does not exist, add it and add int=1

2 Comments

Create a new multidimensional array of types string:int How would you know how big to make this array? Easier to use a Map I think
True, though, by creating the function yourself you can learn the logic yourself in addition to perhaps expanding using more simpler means. But agreed there are lots of ways.

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.