Logical Indexing in JAVA

How to make access array elements using logical indexing in Java?

Matlab / Octave is the 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 Aand logicalarrayin Java. How do I get resultwithout using loops?

+4
source share
2 answers

As @Oleg says , you have a completely different syntax in Java and @ luk2302 mentions you can use Streams

Next 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));

will print

result = [2, 6]

edit If you need to save logicalarray, a possible solution might 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));
+3

- :

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));
    }
}
+2

Source: https://habr.com/ru/post/1683524/


All Articles