Logical indexing in JAVA

Likeunknown

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?

SubOptimal

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]

編集
0

コメントを追加

0

関連記事

分類Dev

pandas apply only returning first value when using logical indexing

分類Dev

What is the logical xor operator in java?

分類Dev

What is the logical xor operator in java?

分類Dev

Why is a Matlab logical indexing operation for thresholding matrix elements superior in performance to a mex implementation?

分類Dev

how to solve the indexing in java programming language

分類Dev

Converting Roman numeral to number logical error java

分類Dev

Converting Roman numeral to number logical error java

分類Dev

ArrayIndexOutOfBoundsException: 1. What is wrong with my indexing? Java

分類Dev

Correct Use of Matcher Groups in Java Regex when using logical OR

分類Dev

java 8 predicate type mismatch, this code seems logical to me

分類Dev

when executing program, extra input command causes logical errors java

分類Dev

Indexing in lucene

分類Dev

Numpy Advanced Indexing and basic indexing

分類Dev

Logical not operator

分類Dev

Logical AND and OR with grep

分類Dev

SUMIF with Logical AND

分類Dev

Conditional indexing with Numpy ndarray

分類Dev

MySQL Indexing : inverted or forward

分類Dev

Positional indexing in F#

分類Dev

.loc indexing changes type

分類Dev

Pandas indexing and Key error

分類Dev

How indexing works in Pandas?

分類Dev

Numpy Indexing FirstBoolean

分類Dev

Pandas DataFrame Advanced Indexing

分類Dev

Numpy advanced indexing fails

分類Dev

issue with substring indexing

分類Dev

Mysql indexing for lengthy query

分類Dev

Defining numpy indexing arrays

分類Dev

SLICC indexing syntax