java - Copying values of array at specific indices to another array -


i came situation have array , need copy specific attributes (i.e. values @ specific indinces) not whole array array.

for example if initial array is:

double[] initarray = {1.0, 2.0, 1.5, 5.0, 4.5}; 

then if wanted copy 2nd, 4th , 5th attribute (i.e. values @ these indices) desired output array be:

double[] reducedarray = {2.0, 5.0, 4.5}; 

i know if indices appear in sequential form, e.g. 1-3 can use system.arraycopy() indices not have aspect.

so, there official way this, besides trivial loop through each value , copy ones needed:

double[] includedattributes = {1, 4, 5}; double[] reducedarray = new double[includedattributes.length]; for(int j = 0; j < includedattributes.length; j++) {     reducedarray[j] = initarray[includedattributes[j]]; } 

using streams, it's one-liner.

given:

int[] indices; double[] source; 

then:

double[] result = arrays.stream(indices).maptodouble(i -> source[i]).toarray(); 

Comments

Popular posts from this blog

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -