NavsTrend
NavsTrend

Reputation: 71

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.

Upvotes: 1

Views: 5720

Answers (6)

Sourish Mukherjee
Sourish Mukherjee

Reputation: 179

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. 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. Hope it helps!

Upvotes: 0

Evgeny Shagov
Evgeny Shagov

Reputation: 21

    public static String isListContainsNumber(List<Integer> nums, int n) {
           return nums.stream().anyMatch(el -> el.equals(n)) ? "YES" : "NO";
    }

Upvotes: 0

Michael
Michael

Reputation: 1184

Using streams:

static String findNumber(List<Integer> arr, int k) {
    return arr.stream()
        .filter(e -> e == k)
        .findFirst()
        .map(e -> "YES")
        .orElse("NO");
}

Upvotes: 0

Istiaque Hossain
Istiaque Hossain

Reputation: 2367

try optimize your code....

way 1 (using for-each loop):

 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";
}

Upvotes: 0

Pavel Smirnov
Pavel Smirnov

Reputation: 4809

You could just use arr.contains() to get a boolean value of whether Integer is on the list or not. An then you can translate this value to YES or NO (if you do really need it):

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

Upvotes: 1

Paolo Mossini
Paolo Mossini

Reputation: 1096

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

Upvotes: 0

Related Questions