'How can I Sum arrays lengths from arraylist Java

How can i sum arrays lenghts from arraylist, i want to get sum of string lenght from arrays and print the sum

the bug is in main

public class Listy {
public static void main(String[] Listy) {

    List<String[]> words = new ArrayList<>();
    words.addAll(Arrays.asList((["Pat"], ["Michał"],))
    System.out.println(getSumOfLenghts(a));




    public static int getSumOfLenghts(List<String[]> words) {
    int sum = 0;

    for (String[] currentarray:words) {
        sum += currentarray.length;
    }
    return sum;
}


Solution 1:[1]

As @shmosel comment, you get the errors because you did not declared a array as java syntax, you have a list of String array:

I edited your code as below and it's work:

public static void main(String[] args) {
    
    List<String[]> words = new ArrayList<>();
    words.add(new String[]{"Pat", "Michal"});
    words.add(new String[]{"Pat 2", "Michal 2"});
    System.out.println(getSumOfLenghts(words));
}

Edit: To answer your question on comment, I have create this example, that contains two function:

  1. getSumOfLenghts this function return how much String in the list

  2. getSumOfEachStringLenghts this function return the sum of all the String in the list.

    public class Listy {
    
    public static void main(String[] args) {
        List<String[]> words = new ArrayList<>();
        words.add(new String[]{"Pat", "Michal"});
        words.add(new String[]{"Pat 2", "Michal 2"});
        System.out.println(getSumOfLenghts(words));
        System.out.println(getSumOfEachStringLenghts(words));
    }
    
    public static int getSumOfLenghts(List<String[]> words) {
        int sumArrElem = 0;
    
        for (String[] currentarray:words) {
            sumArrElem += currentarray.length;
        }
        return sumArrElem;
    }
    
    public static int getSumOfEachStringLenghts(List<String[]> words) {
        int sumForEachElem = 0;
    
        for (String[] currentarray:words) {
            for (String s : currentarray) {
                sumForEachElem += s.length();
            }
        }
        return sumForEachElem;
    }
    }
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1