为了账号安全,请及时绑定邮箱和手机立即绑定

从 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 关注
  • 77 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信