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?
I have a function (countOcc
) which requires a char array (char[][]
), but I wanted to make it possible to use it with a string array (String[]
) using the method toArray
of a string.
public final int countOcc (String[] value) {
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);
}
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);