How to do access array elements using logical indexing in Java?
Matlab/Octave equivalent of what I want to do:
A = [1 2 3 4 5 6]
logicalarray=[0 1 0 0 0 1];
result= A(logical)
which gives result =[2 6]
If I have the same A
and logicalarray
in Java. How would I get that result
without using loops?
As said by @Oleg you have a complete different syntax in Java and as @luk2302 mention you might use Streams
Following snippet
int[] a = {1, 2, 3, 4, 5, 6};
// logicalarray=[0 1 0 0 0 1];
// index is zero-based in Java
int[] result = IntStream.of(1, 5)
.map(i -> a[i])
.toArray();
System.out.println("result = " + Arrays.toString(result));
would print
result = [2, 6]
edit If you need to keep the logicalarray
a possible solution could be
int[] a = {1, 2, 3, 4, 5, 6};
int[] logicalarray = {0, 1, 0, 0, 0, 1};
int[] result = IntStream.range(0, logicalarray.length) // create a stream of array indexes
.filter(i -> logicalarray[i] == 1) // filter the indexes which are 1 in logicalarray
.map(i -> a[i]) // map the related value from array a
.toArray(); // create an array of the values
System.out.println("result = " + Arrays.toString(result));
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加