2675. Array of Objects to Matrix
Explanation:
Given an array of objects, we need to convert it into a matrix where each row represents an object and each column represents a property of the object.
To achieve this, we can follow these steps:
- Get the list of properties from the first object to determine the number of columns in the matrix.
- Initialize a 2D matrix where the number of rows is the size of the input array and the number of columns is the number of properties.
- Iterate through the input array and populate the matrix by mapping each object to a row and each property to a column in the matrix.
The time complexity of this solution is O(n * m), where n is the number of objects in the input array, and m is the number of properties in each object. The space complexity is O(n * m) to store the resulting matrix.
:
import java.util.List;
public int[][] arrayToMatrix(List<Object> objects) {
if (objects == null || objects.isEmpty()) return new int[0][0];
int n = objects.size();
int m = objects.get(0).getClass().getDeclaredFields().length;
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
Object obj = objects.get(i);
int j = 0;
for (java.lang.reflect.Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
matrix[i][j++] = field.getInt(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return matrix;
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.