How to cast Object Array to Map Array
It seems like you're confusing an array and ArrayList.
An array is a data-container that occupies a contiguous block of memory and has a fixed length.
ArrayList is a built-in implementation of the Dynamic array data structure, which is backed by an array, but contrary to a plain array it's capable to grow is size and provides a lot of useful behavior.
If your background is JavaScript, then ArrayList is closer to arrays in JavaScript.
Regarding casting, as I've said, you shouldn't use the Object in the first place. Your list should be of type List<Map<String, Integer>> then there would be no problem.
If we would try to convert this list objects into its actual type - no luck:
List<Map<String, Integer>> fruitConverted = (List<Map<String, Integer>>) fruit; // that would not compile, the compiler will not allow that
That work around it to fool the compiler by using an intermediate variable of so-called row type.
List rowList = fruit;
List<Map<String, Integer>> fruitConverted = rowList;
In this case the compiler will issue a warning, but the code will compile. But you should be aware that a vary bad stale of coding.
For more information on type conversion see.
I would like to remove one of the key in each dictionary
In your code, you're trying to create a new list in different ways, so it seems like you want to keep the previous version of the list with all maps intact.
If so you can use streams to create a duplicate of every entry (excluding entries with an undesired key "orange") for each map and then collect then into a list.
public static void main(String[] args) {
List<Object> fruit =
List.of(Map.of("apple", 3, "orange", 4),
Map.of("apple", 13, "orange", 2),
Map.of("apple", 1, "orange", 8));
List<Map<String, Integer>> newList = fruit.stream()
.map(map -> ((Map<String, Integer>) map).entrySet().stream()
.filter(entry -> !entry.getKey().equals("orange")) // will retain entries with key that not equal to "orange"
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)))
.collect(Collectors.toList());
System.out.println(newList);
}
Output:
[{apple=3}, {apple=13}, {apple=1}]
But if you don't need the previous version of the list, then you can use a combination of forEach() an remove().
proper way to cast the type- In Java, a good practice is to avoid type casting. Your list should be of typeList<Map<Integer, Integer>in the first place. By usingObjectas a generic type and performing type-casts, you're relinquishing the built-in type-safety mechanism, i.e. the compiler will not help you with verifying the code. And it makes it difficult to read.