3 回答
TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
我告訴你最簡單的方法...
List<Integer> given_list = new ArrayList<>(Arrays.asList(new Integer[] {0,4,5,56,3, 2000, 453}));
given_list.removeIf(element -> element > 100);
System.out.println(given_list);
TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊
使用 Java 8 Stream API,這可以通過一行代碼來實(shí)現(xiàn):
Arrays.stream(given_list).filter(x -> x<100).toArray()
上面的代碼行創(chuàng)建了一個(gè)新數(shù)組,并且不修改原始數(shù)組。
TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
import java.util.ArrayList;
import java.util.List;
public class DeleteFromList {
public static void main(String[] args) {
int[] given_list = {0,4,5,56,3, 2000,8,345, 453,};
//since there is no direct way to delete an element from the array we have to use something other than array, like a list.
List<Integer> list = new ArrayList<Integer>();
//this changes the whole array to list
for (int i : given_list){
list.add(i);
}
//this iterates through the list and check each element if its greater then 100
for(int i=0;i<list.size();i++){
if(list.get(i) > 100){
list.remove(i);
i--; // this is because everytime we delete an element, the next comes in place of it so we need to check new element.
}
}
//print out the new list which has all the elements which are less than 100
System.out.println(list);
}
}
由于無法從數(shù)組中刪除元素,因此我們必須將數(shù)組更改為列表,然后對該列表進(jìn)行操作,以便我們可以根據(jù)需要刪除元素。
添加回答
舉報(bào)
