如何使用Java中的逻辑索引来访问数组元素?
Matlab / Octave相当于我想做的事情:
A = [1 2 3 4 5 6]
logicalarray=[0 1 0 0 0 1];
result= A(logical)
,提供result =[2 6]
如果我在Java中有相同的A
和logicalarray
。如何在不使用循环的情况下获得result
?
答案 0 :(得分:3)
正如@Oleg所述,您在Java中使用完全不同的语法,并且@luk2302提到您可能会使用Streams
以下摘录
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));
会打印
result = [2, 6]
修改如果您需要保持logicalarray
可能的解决方案
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));
答案 1 :(得分:2)
您可以尝试这样的事情:
import java.util.Arrays;
import java.util.stream.IntStream;
public class Example {
public static void main(String[] args) {
int[] A = {1, 2, 3, 4, 5, 6};
int[] L = {0, 1, 0, 0, 0, 1};
int[] n = IntStream.range(0, A.length).map(i -> A[i] * L[i]).filter(i->i>0).toArray();
System.out.println(Arrays.toString(n));
}
}