Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert for each loop into lambda for each?

I have the code below where i take an array of string and i convert to an array of char.
How can i transform it so i use the lambda function?

    int m = 1;
    for (String v : value) if (v.length() >= m) m = v.length();
    char[][] a = new char[value.length][m];
    for (int i = 0; i < value.length; i++) a[i] = value[i].toCharArray();
    return countOcc(a);
 }

i tried using Arrays.stream().foreach() like below but when i do things like c++ it gives me an error

    public final int countOcc (String[] value) {
    int m = 1;
    Arrays.stream(value).forEach(e -> {
        if (e.length() >= m) m = e.length();
    });
    char[][] a = new char[value.length][m];
    int c = 0;
    Arrays.stream(value).forEach(e -> {
        a[c] = e.toCharArray();
        c++;
    });
    return countOcc(a);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you are trying to convert a String[] to a char[][] then do something like:

String[] value = {"foo", "bar", "fizz"};
char[][] a = Arrays.stream(value).map(s -> s.toCharArray()).toArray(char[][]::new);

then call your other method

return countOcc(a);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading