double array to boolean array with logical operation in java
double array to boolean array with logical operation in java
我有一个操作要在 java 中进行,如果不执行 for 循环我无法找到解决方法,为了提高计算效率我真的很想避免。
我曾经在 Matlab 中编程并且它很容易做到,但在 java 中似乎更棘手。我的问题是……这个 Matlab 代码的 java 等价物是什么:
A = [1;-3;2;2;5-7;0];
A<1;
ans =
0
1
0
0
1
1
在 java 我在漫游互联网时尝试了这个方法。
Integer[] array = {-1,2,-3,4,-5,-6};
List<Integer> result = Arrays.stream(array).filter(w -> w < 1 )
.collect(Collectors.toList());
在这个例子中 result = {-1,-3,-5,-6}
但我希望有 result = {1,0,1,0,1,1}
老派解决方案(假设 X
是某个 int 值;并且 `intValues' 代表某种 collection/array 的整数或整数):
List<Boolean> lessThanX = new ArrayList<>();
for (int i : intValues) {
lessThanX.add( i < X );
}
如今,使用流:
intValues.stream().map( i -> i < X ).collect(Collectors.asList());
(或类似的东西......因为问题包含尝试自己的零努力 - 我省略了交叉检查我的输入 - 它只是作为让你前进的灵感)
int[] a = {1,-3,2,2,-2,0};
Arrays.stream(a).forEach(i -> System.out.println(i < 1 ? 1 : 0));
这看起来确实应该是一个简单的循环函数。
double[] outputArray = {1, -3, 2, 2, 5, -7, 0};
boolean[] outputArray = new boolean[inputArray.length];
for (int i = 0; i < inputArray.length; i++) {
outputArray[i] = inputArray[i]<1;
}
这可以很容易地更改为以 outputArray
作为参数的方法调用,这可能最适合您的需要。
public static int[] convertToBinary(int[] decimal, int compareInt){
int[] binary = new int[decimal.length];
int index = 0;
Arrays.stream(decimal).forEach( dec -> binary[index++] = dec < compareInt ? 1 : 0 );
return binary;
}
我有一个操作要在 java 中进行,如果不执行 for 循环我无法找到解决方法,为了提高计算效率我真的很想避免。 我曾经在 Matlab 中编程并且它很容易做到,但在 java 中似乎更棘手。我的问题是……这个 Matlab 代码的 java 等价物是什么:
A = [1;-3;2;2;5-7;0];
A<1;
ans =
0
1
0
0
1
1
在 java 我在漫游互联网时尝试了这个方法。
Integer[] array = {-1,2,-3,4,-5,-6};
List<Integer> result = Arrays.stream(array).filter(w -> w < 1 )
.collect(Collectors.toList());
在这个例子中 result = {-1,-3,-5,-6}
但我希望有 result = {1,0,1,0,1,1}
老派解决方案(假设 X
是某个 int 值;并且 `intValues' 代表某种 collection/array 的整数或整数):
List<Boolean> lessThanX = new ArrayList<>();
for (int i : intValues) {
lessThanX.add( i < X );
}
如今,使用流:
intValues.stream().map( i -> i < X ).collect(Collectors.asList());
(或类似的东西......因为问题包含尝试自己的零努力 - 我省略了交叉检查我的输入 - 它只是作为让你前进的灵感)
int[] a = {1,-3,2,2,-2,0};
Arrays.stream(a).forEach(i -> System.out.println(i < 1 ? 1 : 0));
这看起来确实应该是一个简单的循环函数。
double[] outputArray = {1, -3, 2, 2, 5, -7, 0};
boolean[] outputArray = new boolean[inputArray.length];
for (int i = 0; i < inputArray.length; i++) {
outputArray[i] = inputArray[i]<1;
}
这可以很容易地更改为以 outputArray
作为参数的方法调用,这可能最适合您的需要。
public static int[] convertToBinary(int[] decimal, int compareInt){
int[] binary = new int[decimal.length];
int index = 0;
Arrays.stream(decimal).forEach( dec -> binary[index++] = dec < compareInt ? 1 : 0 );
return binary;
}