亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 int 數組中刪除所有大于 100 的值

從 int 數組中刪除所有大于 100 的值

眼眸繁星 2023-09-20 19:18:13
給定一個整數列表 1,2,3 等。刪除所有大于 100 的值?這個的JAVA代碼是什么?import java.util.ArrayList;import java.util.List;public class Main {public static void main(String[] args) {    int[] given_list = {0,4,5,56,3, 2000, 453,};    }}
查看完整描述

3 回答

?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

我告訴你最簡單的方法...


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


查看完整回答
反對 回復 2023-09-20
?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

使用 Java 8 Stream API,這可以通過一行代碼來實現:

Arrays.stream(given_list).filter(x -> x<100).toArray()

上面的代碼行創建了一個新數組,并且不修改原始數組。


查看完整回答
反對 回復 2023-09-20
?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

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


   }

}


由于無法從數組中刪除元素,因此我們必須將數組更改為列表,然后對該列表進行操作,以便我們可以根據需要刪除元素。


查看完整回答
反對 回復 2023-09-20
  • 3 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號