![](/img/trans.png)
[英]How do I Take certain elements of a String array and create a new array java
[英]How do I create a new array with fewer elements than a given array?
在 Java 中,當我基於作為參數傳入的數組構建新數組時。 例如,假設我想用給定數組的所有值構建一個數組,除了 sevens,所以我想取 {5,7,8,9,7,3} 並返回 {5,8,9,3 } 不修改輸入數組。 在 python 中,這將非常簡單,我會這樣做:
def no7s(x):
y=[]
for num in x:
if num!=7:
y+=[num]
return y
在 java 中,這似乎要復雜得多。 這是我嘗試過的:
public static int[] no7s(int[] x){
int size=0;
for (int num: x){
if (num!=7){
size+=1;
}
}
int[] y = new int[size];
for (int i=0; i<x.length; i++){
if (x[i]!=7){
y[i]=x[i];
}
}
return y;
}
我對最后一個 for 循環感到困惑; 我現在所擁有的不起作用,但我不確定我應該做什么。 我很確定問題在於 x.length>size,但我不知道如何解釋這一點。
在 Java 中,答案是流。
這是用流重寫的no7s
:
public static int[] no7s(int[] x) {
return Arrays.stream(x)
.filter(i -> i != 7)
.toArray();
}
確保包括import java.util.Arrays;
在 java 文件的頂部。
通常,不要嘗試在 arrays 大小等瑣碎的事情上優化您的代碼。 JVM 及更低級別有幾層優化。
您希望專注於更高級別的優化(多線程、資源池等)。
如果你想使用命令式風格(舊式):
int[] toCopy = {5,7,8,9,7,3};
List<Integer> array = new ArrayList<>();
for (int current : toCopy) {
if (current != 7) {
array.add(current);
}
}
如果您想使用流(推薦),請參閱 Adam Griffiths 的回答:
public static int[] no7s(int[] x) {
return Arrays.stream(x)
.filter(i -> i != 7)
.toArray();
}
如果尚未完成,我強烈建議您查看Object Oriented Programming ,因為這就是 Java 的全部內容。
我還建議使用函數式編程(如流,在 Java 8 中引入),因為一旦習慣了它就更容易閱讀和維護。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.