简体   繁体   English

在java中的arraylist中搜索整数

[英]Searching for an integer in arraylist in java

public class FindNumber {

            static String findNumber(List<Integer> arr, int k) {
                String res = "YES";
    //Unable to identify problem with this part of the code
                for (int i = 0; i < arr.size(); i++) {
                    if (k == arr.get(i))
                        res = "YES";
                    else
                        res = "NO";

                }

                return res;

            }
}

Above code returns NO as the answer even if the integer is present in the list.即使列表中存在整数,上面的代码也会返回 NO 作为答案。

You could just use arr.contains() to get a boolean value of whether Integer is on the list or not.您可以使用arr.contains()来获取Integer是否在列表中的布尔值。 An then you can translate this value to YES or NO (if you do really need it):然后您可以将此值转换为YESNO (如果您确实需要它):

String yesNo = arr.contains(k) ? "YES" : "NO";

This will work:这将起作用:

static String findNumber(List<Integer> arr, int k) {
            String res = "YES";
            for (int i = 0; i < arr.size(); i++) {
                if (k == arr.get(i))
                    res = "YES";
                    break;
                else
                    res = "NO";

            }

            return res;

        }

Once you find the integer you have to stop the loop, and you can do this using a break一旦你找到整数,你就必须停止循环,你可以使用break来做到这一点

try optimize your code....尝试优化您的代码....

way 1 (using for-each loop):方式1(使用for-each循环):

 static String findNumber(List<Integer> arr, int k) { 
        for (Integer integer : arr) {
            if (integer == k) {
                return "YES";
            }
        }
        return "NO"; 
    }

another way is (using ternary operator) :另一种方法是(使用三元运算符):

static String findNumber(List<Integer> arr, int k) { 
    return arr.contains(k) ? "YES" : "NO";
}

Using streams:使用流:

static String findNumber(List<Integer> arr, int k) {
    return arr.stream()
        .filter(e -> e == k)
        .findFirst()
        .map(e -> "YES")
        .orElse("NO");
}
    public static String isListContainsNumber(List<Integer> nums, int n) {
           return nums.stream().anyMatch(el -> el.equals(n)) ? "YES" : "NO";
    }

The main problem with your code is that even if it finds an integer object in the ArrayList, after setting res = Yes, it still continues the iteration.你的代码的主要问题是,即使在ArrayList中找到一个整数对象,设置res = Yes后,它仍然继续迭代。 Therefore there is a possibility that there might be other values inside the list of not the desired data type, thereby setting res back to No. The solution here is to use a jump statement such as break which would terminate the loop process as soon as an integer is encountered.因此,列表中可能存在其他不是所需数据类型的值,从而将 res 设置回 No。 这里的解决方案是使用跳转语句,例如 break,它会在遇到整数。 Hope it helps!希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM