I have an array Object[]
which contains elements that are arrays String[]
. How can I get these elements as String[]
?
Object[] arr = Files.lines(filePath)
.map(n -> n.split(","))
.filter(n -> n.length > 1)
.toArray();
for (Object value : arr) {
....value[1].... // compilation error here
}
CodePudding user response:
Compiler will not cast an Object
into an array automatically, hence you're getting an error.
And instead of performing casting you can provide toArray()
with a generator function to obtain an array String[][]
(where each element is an array String[]
) instead of generating an array Object[]
as a result of the stream execution.
String[][] arr = Files.lines(filePath)
.map(n -> n.split(","))
.filter(n-> n.length > 1)
.toArray(String[][]::new);
CodePudding user response:
You can convert the iterated item into a String
array like this
import java.util.*;
import java.lang.*;
import java.io.*;
// The main method must be in a class named "Main".
class Main {
public static void main(String[] args) {
Object[] arr = new Object[] {
new String[] {"a", "b", "c"},
new String[] {"d", "e", "f"},
new String[] {"g", "h", "i"}
};
for (Object value : arr) {
System.out.println(((String[])value)[1]);
}
}
}