Search code examples
javaarraysloopsfor-loopmultidimensional-array

Find how many times a value appears in a 2D array and store that number in another 1D array


I have searched so many questions on stack overflow and google results on how to do specifically what I want to do, but none of them seem to apply to what I am trying to do.

I just need to simply make a for loop to cycle through a 2D array's rows that were filled from a file and find instances where the row has a Y, however, the rows also have a number from 1-24. Rows look like: Team# Y/N and I need to just count how many times a team has Y in its row, and store it to print later. Example:

Team 1 had a count of 3
Team 5 had a count of 4

I need to find out how to iterate through this 2D array of data and find how many times each team had a Y in its row and then store it to the right team.


Solution

  • Algorithm

    1. Iterate over each row of the 2D Array
    2. Count how many columns match "Y"
    3. Store the value as wanted

    Knowing the string will increase in lenght each iteration it's useful to use StringBuilder class which allows better work with dynamic Strings. And for counting the matches we can use the benefits of the Stream class, filter the values and then the count will be the wanted value.

    As we are working with functions you must work with Java 8 or greater:

    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            String[][] table = {
                    {"1", "Y", "N", "Y"},
                    {"2", "Y", "Y", "Y"},
                    {"3", "N", "N", "Y"}};
    
            StringBuilder scores = new StringBuilder(table.length * 5);
            for (String[] row : table) {
                scores.append(row[0])
                    .append(": ")
                    .append(Arrays.stream(row)
                    .filter(str -> str.equalsIgnoreCase("Y"))
                    .count()
                ).append('\n');
            }
            System.out.println(scores.toString());
        }
    }