Converting an array of objects to an array of their primitive types
Unfortunately, there's nothing in the Java platform that does this. Btw, you also need to explicitly handle null
elements in the Integer[]
array (what int
are you going to use for those?).
Convert an array of objects into an array of arrays with Python
Check out the powerful pandas string operators.
In this case, series.str.strip
and series.str.split
will do the trick:
In [11]: df['velocity'].str.strip('()').str.split(', ', expand=True).to_numpy()
Out[11]:
array([['a1', 'a2', 'a3'],
['b1', 'b2', 'b3'],
['c1', 'c2', 'c3'],
['z1', 'z2', 'z3']], dtype=object)
If your data is actually float types, you can add .astype(float)
to convert the strings to float64:
In [12]: df['velocity'].str.strip('()').str.split(', ', expand=True).to_numpy().astype(float)
Out[12]:
array([[-7143.645 , -825.2191, -2463.361 ],
[-7143.645 , -825.2191, -2463.361 ],
[-7087.896 , -1058.8871, -2533.3374],
[-7024.463 , -1291.3812, -2600.547 ],
[-6953.418 , -1522.4622, -2664.9265]])
Performance considerations
Note that the vectorized string operators are significantly faster for larger arrays compared with a row-wise operation such as ast.literal_eval
.
For an array with 10,000 rows and four columns:
In [23]: s = pd.DataFrame(np.random.random(size=(10000,4))).apply(lambda x: '({},{},{},{})'.format(x[0], x[1], x[2], x[3]), axis=1)
In [24]: s
Out[24]:
0 (0.9134272324343906,0.09784434338612968,0.1064...
1 (0.6171577052744037,0.552712839936354,0.684161...
2 (0.05253084132451025,0.6216173862765718,0.3920...
3 (0.39577548909770743,0.35020447632615737,0.632...
4 (0.4761450474353096,0.20003567087846386,0.2113...
...
9995 (0.3618865364493633,0.4947066480156196,0.17413...
9996 (0.4083358148057057,0.09394431583700069,0.8712...
9997 (0.9466315666988651,0.4692990331960303,0.04969...
9998 (0.22868850839996946,0.4712850069678187,0.4834...
9999 (0.1525379507879958,0.6019087151036507,0.07105...
Length: 10000, dtype: object
the pandas string operators are more than 10 times faster
In [26]: %%timeit
...: np.vstack(s.apply(ast.literal_eval))
...:
...:
160 ms ± 13.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [27]: %%timeit
...: s.str.strip('()').str.split(', ', expand=True).to_numpy()
...:
...:
14.2 ms ± 704 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Cast primitive type array into object array in java
Primitive type cannot be transformed in this way.
In your case, there is an array of double values, cause of 3.14.
This will work:
List<Object> objectList = new ArrayList<Object>();
objectList.addAll(Arrays.asList(0,1,2,3.14,4));
Even this works :
List<Object> objectList = new ArrayList<Object>();
objectList.addAll(Arrays.asList(0,"sfsd",2,3.14,new Regexp("Test")));
for(Object object:objectList)
{
System.out.println(object);
}
UPDATE
Ok, there as there was said, there is not direct way to cast a primitive array to an Object[].
If you want a method that transforms any array in String, I can suggest this way
public class CastArray {
public static void main(String[] args) {
CastArray test = new CastArray();
test.TestObj(new int[]{1, 2, 4});
test.TestObj(new char[]{'c', 'a', 'a'});
test.TestObj(new String[]{"fdsa", "fdafds"});
}
public void TestObj(Object obj) {
if (!(obj instanceof Object[])) {
if (obj instanceof int[]) {
for (int i : (int[]) obj) {
System.out.print(i + " ");
}
System.out.println("");
}
if (obj instanceof char[]) {
for (char c : (char[]) obj) {
System.out.print(c + " ");
}
System.out.println("");
}
//and so on, for every primitive type.
} else {
System.out.println(Arrays.asList((Object[]) obj));
}
}
}
Yes, it's annoying to write a loop for every primitive type, but there is no other way, IMHO.
Converting Array of Primitives to Array of Containers in Java
Apache Commons
Apache Commons / Lang has a class ArrayUtils that defines these methods.
- All methods called
toObject(...)
convert from primitive array to wrapper array - All called
toPrimitive(...)
convert
from wrapper object array to
primitive array
Example:
final int[] original = new int[] { 1, 2, 3 };
final Integer[] wrappers = ArrayUtils.toObject(original);
final int[] primitivesAgain = ArrayUtils.toPrimitive(wrappers);
assert Arrays.equals(original, primitivesAgain);
Guava
But then I'd say that Arrays of wrapped primitives are not very useful, so you might want to have a look at Guava instead, which provides Lists of all numeric types, backed by primitive arrays:
List<Integer> intList = Ints.asList(1,2,3,4,5);
List<Long> longList = Longs.asList(1L,2L,3L,4L,5L);
// etc.
The nice think about these array-backed collections is that
- they are live views (i.e. updates to the array change the list and vice-versa)
- the wrapper objects are only created when needed (e.g. when iterating the List)
See: Guava Explained / Primitives
Java 8
On the other hand, with Java 8 lambdas / streams, you can make these conversions pretty simple without using external libraries:
int[] primitiveInts = {1, 2, 3};
Integer[] wrappedInts = Arrays.stream(primitiveInts)
.boxed()
.toArray(Integer[]::new);
int[] unwrappedInts = Arrays.stream(wrappedInts)
.mapToInt(Integer::intValue)
.toArray();
assertArrayEquals(primitiveInts, unwrappedInts);
double[] primitiveDoubles = {1.1d, 2.2d, 3.3d};
Double[] wrappedDoubles = Arrays.stream(primitiveDoubles)
.boxed()
.toArray(Double[]::new);
double[] unwrappedDoubles = Arrays.stream(wrappedDoubles)
.mapToDouble(Double::doubleValue)
.toArray();
assertArrayEquals(primitiveDoubles, unwrappedDoubles, 0.0001d);
Note that the Java 8 version works for int
, long
and double
, but not for byte
, as Arrays.stream() only has overloads for int[]
, long[]
, double[]
or a generic object T[]
.
How do I convert an array of objects into an object (dynamically) in JavaScript
Assuming that each object in your list has the same keys you could get the keys of the first object
const keys = Object.keys(arr[0])
and then map through the keys with your above approach
const returnObj = {}
keys.forEach(key => {
returnObj[key] = arr.map(item => item[key])
})
return returnObj
Convert key value pair to array of objects
There exists a method Object.entries
that turns object into list of keys and values already, mapping it to match your required format should not be difficult.
const data = {good: 'value1', key2: 'value2', key3: 'value3'};
const result = Object.entries(data).map(([key, value]) => ({key, value}))
console.log(result)
How do you convert a two dimensional array of a boxed type to a two dimensional array of the corresponding primitive type?
You have to iterate over the list and convert each element into an int primitive. Arrays are special kinds of objects in Java, so int[][]
and Integer[][]
are completely unrelated to each other. It would be like trying to cast a Foo
to a Bar
. Java does support implicit casts from Integer
to int
however. That's called auto-boxing, and you can see it at work below at the line primitives[i][j] = documents[i][j]
where a single Integer
is implicitly cast to a primitive int
.
int[][] convertToPrimitives(Integer[][] documents) {
int[][] primitives = new int[documents.length][];
for (int i=0;i<documents.length;i++) {
primitives[i] = new int[documents[i].length];
for (int j=0;j<documents[i].length;j++) {
primitives[i][j] = documents[i][j];
}
}
return primitives;
}
Related Topics
Platform Independent Paths in Java
Deserializing into a Hashmap of Custom Objects with Jackson
Issue Using Imageio.Write Jpg File: Pink Background
Finding the Second Highest Number in Array
What Is the Purpose of @Namedarg Annotation in Javafx 8
How to Compile & Run Java Program in Another Java Program
Get MAC Address on Local MAChine with Java
Java 8: Difference Between Method Reference Bound Receiver and Unbound Receiver
Best Way to Encode Text Data for Xml in Java
Does Java Have a Hashmap with Reverse Lookup
"Unable to Acquire Application Service" Error While Launching Eclipse
Java Ioexception "Too Many Open Files"
How to Create a Topic in Kafka Through Java
How to Pass Arithmetic Operators to a Method in Java
Noclassdeffounderror in Java: Com/Google/Common/Base/Function
Java Inetaddress.Getlocalhost(); Returns 127.0.0.1 ... How to Get Real Ip