Cannot create nested ArrayList from Array in Java
I am trying to create a nested list from an array.
But I have a problem while converting Object
to String
:
Object[] array = new Object[] {
new String[] {"add, hack"},
new String[] {"add, hackerrank"},
new String[] {"find, hac"},
new String[] {"find, hak"}
};
List<List<String>> list = Arrays.asList(Arrays.asList((array.toString())));
So, how can I convert it properly?
Here is the method that reserves the List<List<String>>
:
public static List<Integer> contacts(List<List<String>> queries) {
for (List<String> query : queries) {
String operation = query.get(0); // --> gives "add, hack" (I expect "add")
String word = query.get(1);
}
}
One more solution assuming you want to start from Object[] array - first transforms to list of String[] using casting and then maps every String[] to List:
List<String[]> arrList = new ArrayList<>();
for (Object o : array)
arrList.add((String[]) o);
List<List<String>> strList = arrList.stream()
.map(Arrays::asList)
.collect(Collectors.toList());