XYZ
XYZ

Reputation: 382

Java Integer (java.lang.Integer) Array division and other math operations

I would like to divide a java.lang.Integer array and saved the result into a java.lang.Double array. I search over the Internet and could not find useful information (most of the search regarding java.lang.Integer class leads to the primitive type int operations, as Division of integers in Java, and this Integer division in Java).

My following code won't work

    Integer[] FixedDays = {1, 2, 7, 14, 30, 60, 90, 180, 548, 730, 1095, 1460, 1825};
    Double[] Ts = FixedDays / 365.0;

Is there a quick way to do the division regarding java.lang.Integer (or more generally the Number class and other basic math operation.)? Is there some math package which support such Number array operations?

Upvotes: 1

Views: 233

Answers (2)

dreamcrash
dreamcrash

Reputation: 51593

You can do it pretty concisely with Java Streams:

Arrays.stream(FixedDays).map(i -> i / 365.0).toArray();

or

double[] doubles = Arrays.stream(FixedDays)
                         .map(i -> i / 365.0)
                         .mapToDouble(Double::doubleValue)
                         .toArray();

or

Double[] Ts = Arrays.stream(FixedDays)
                    .map(i -> i / 365.0)
                    .toArray(Double[]::new);

Upvotes: 2

Alan Rusnak
Alan Rusnak

Reputation: 247

You have to loop through each element

Integer[] FixedDays = {1, 2, 7, 14, 30, 60, 90, 180, 548, 730, 1095, 1460, 1825};
Double[] Ts = new Double[FixedDays.length];
        
for(int i = 0; i < FixedDays.length; i++) {
  Ts[i] = FixedDays[i] / 365.0;
}

Or you can use streams for a more concise solution

Upvotes: 1

Related Questions