从 int 数组中删除所有大于 100 的值

给定一个整数列表 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,};



    }

}


眼眸繁星
浏览 115回答 3
3回答

ITMISS

我告诉你最简单的方法...List<Integer> given_list&nbsp; = new ArrayList<>(Arrays.asList(new Integer[] {0,4,5,56,3, 2000, 453}));given_list.removeIf(element -> element > 100);System.out.println(given_list);

慕慕森

使用 Java 8 Stream API,这可以通过一行代码来实现:Arrays.stream(given_list).filter(x -> x<100).toArray()上面的代码行创建了一个新数组,并且不修改原始数组。

月关宝盒

import java.util.ArrayList;import java.util.List;public class DeleteFromList {public static void main(String[] args) {&nbsp; &nbsp;int[] given_list = {0,4,5,56,3, 2000,8,345, 453,};&nbsp;&nbsp; &nbsp;//since there is no direct way to delete an element from the array we have to use something other than array, like a list.&nbsp; &nbsp;List<Integer> list = new ArrayList<Integer>();&nbsp; &nbsp;//this changes the whole array to list&nbsp; &nbsp;for (int i : given_list){&nbsp; &nbsp; &nbsp; list.add(i);&nbsp; &nbsp;}&nbsp; &nbsp;//this iterates through the list and check each element if its greater then 100&nbsp; &nbsp;for(int i=0;i<list.size();i++){&nbsp; &nbsp; &nbsp; if(list.get(i) > 100){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;list.remove(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;i--;&nbsp; &nbsp; &nbsp;// this is because everytime we delete an element, the next comes in place of it so we need to check new element.&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}&nbsp; &nbsp;//print out the new list which has all the elements which are less than 100&nbsp; &nbsp;System.out.println(list);&nbsp; &nbsp;}}由于无法从数组中删除元素,因此我们必须将数组更改为列表,然后对该列表进行操作,以便我们可以根据需要删除元素。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java