【问题标题】:remove all values greater than 100 from int array从 int 数组中删除所有大于 100 的值
【发布时间】:2020-02-01 23:14:48
【问题描述】:

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


    }
}

【问题讨论】:

  • 这不是一个供人们为您做作业的网站。你必须先尝试自己编写代码,当你遇到问题时,你发布你的代码(在你先做研究之后)不起作用,我们会告诉你它有什么问题。
  • Arrays.stream(given_list).filter(i -> i <= 100).toArray()

标签: java arraylist removeall


【解决方案1】:

使用 Java 8 Stream API,这可以在一行代码中实现:

Arrays.stream(given_list).filter(x -> x

上面的代码行创建了一个新数组并且不修改原始数组。

【讨论】:

    【解决方案2】:
    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);
    
       }
    }
    
    

    由于无法从数组中删除元素,我们必须将数组更改为列表,然后对该列表进行操作,以便我们可以根据需要删除元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-28
      • 2021-11-09
      • 1970-01-01
      • 2016-07-13
      • 2015-12-30
      相关资源
      最近更新 更多