在arraylist中查找特定范围内的数字

Finding numbers within a certain range in an arraylist

我有一个整数数组列表,用于收集用户输入的数字。我必须使用一种方法在数组中显示 <= 50 的数字。我该怎么做?

public static double levelR(List<Integer> marks){
  for (int i= marks.get(0); i<= 50; i++){
      System.println(marks.get(i));  
}

到目前为止我只知道这个方法,我不知道下一步该怎么做。

你不需要对数组进行排序来解决这个问题。以下是您的操作:

  • 首先编写一个循环,打印数组的所有元素,而不考虑值
  • 修改您的循环以跳过打印大于 50 的数字。有两种方法可以做到这一点 - 添加一个 if 在大于 50 的数字上使用 continue,或者添加一个 if围绕打印。

在Java8:

中占一行
// Given: List<Integer> marks;
marks.stream().filter(x -> x <= 50).forEach(System.out::println);

这是示例,只是打印列表中 <=50

的值
public class ArrayListDemo {
public static void main(String[] args){
    List<Integer> list = new ArrayList<Integer>();
    list.add(10);
    list.add(60);
    list.add(70);
    list.add(30);
    list.add(40);
    list.add(50);

    System.out.println(list);

    for (Integer singleValue: list) {
        if(singleValue<=50) 
            System.out.println(singleValue);
    }
}

}

输出: [10, 60, 70, 30, 40, 50]
10
30
40
50

您也可以创建一个新列表,并根据您的条件存储在其中。