[java] Java, Simplified check if int array contains int

Basically my mate has been saying that I could make my code shorter by using a different way of checking if an int array contains an int, although he won't tell me what it is :P.

Current:

public boolean contains(final int[] array, final int key) {
    for (final int i : array) {
        if (i == key) {
            return true;
        }
    }
    return false;
}

Have also tried this, although it always returns false for some reason.

public boolean contains(final int[] array, final int key) {
    return Arrays.asList(array).contains(key);
}

Could anyone help me out?

Thank you.

This question is related to java arrays int contains

The answer is


You can convert your primitive int array into an arraylist of Integers using below Java 8 code,

List<Integer> arrayElementsList = Arrays.stream(yourArray).boxed().collect(Collectors.toList());

And then use contains() method to check if the list contains a particular element,

boolean containsElement = arrayElementsList.contains(key);

Guava offers additional methods for primitive types. Among them a contains method which takes the same arguments as yours.

public boolean contains(final int[] array, final int key) {
    return Ints.contains(array, key);
}

You might as well statically import the guava version.

See Guava Primitives Explained


Solution #1

Since the original question only wants a simplified solution (and not a faster one), here is a one-line solution:

public boolean contains(int[] array, int key) {
    return Arrays.toString(array).matches(".*[\\[ ]" + key + "[\\],].*");
}

Explanation: Javadoc of Arrays.toString() states the result is enclosed in square brackets and adjacent elements are separated by the characters ", " (a comma followed by a space). So we can count on this. First we convert array to a string, and then we check if key is contained in this string. Of course we cannot accept "sub-numbers" (e.g. "1234" contains "23"), so we have to look for patterns where the key is preceded with an opening bracket or a space, and followed by a closing bracket or a comma.

Note: The used regexp pattern also handles negative numbers properly (whose string representation starts with a minus sign).

Solution #2

This solution is already posted but it contains mistakes, so I post the correct solution:

public boolean contains(int[] array, int key) {
    Arrays.sort(array);
    return Arrays.binarySearch(array, key) >= 0;
}

Also this solution has a side effect: it modifies the array (sorts it).


Depending on how large your array of int will be, you will get much better performance if you use collections and .contains rather than iterating over the array one element at a time:

import static org.junit.Assert.assertTrue;
import java.util.HashSet;

import org.junit.Before;
import org.junit.Test;

public class IntLookupTest {

int numberOfInts = 500000;
int toFind = 200000;
int[] array;

HashSet<Integer> intSet;

@Before
public void initializeArrayAndSet() {
    array = new int[numberOfInts];
    intSet = new HashSet<Integer>();
    for(int i = 0; i < numberOfInts; i++) {
        array[i] = i;
        intSet.add(i);
    }
}

@Test
public void lookupUsingCollections() {
    assertTrue(intSet.contains(toFind));
}

@Test
public void iterateArray() {
    assertTrue(contains(array, toFind));

}

public boolean contains(final int[] array, final int key) {
    for (final int i : array) {
        if (i == key) {
            return true;
        }
    }
    return false;
}
}

You could simply use ArrayUtils.contains from Apache Commons Lang library.

public boolean contains(final int[] array, final int key) {     
    return ArrayUtils.contains(array, key);
}

this worked in java 8

public static boolean contains(final int[] array, final int key)
{
return Arrays.stream(array).anyMatch(n->n==key);
}

1.one-off uses

List<T> list=Arrays.asList(...)
list.contains(...)

2.use HashSet for performance consideration if you use more than once.

Set <T>set =new HashSet<T>(Arrays.asList(...));
set.contains(...)

Try this:

public static void arrayContains(){
    int myArray[]={2,2,5,4,8};

    int length=myArray.length;

    int toFind = 5;
    boolean found = false;

    for(int i = 0; i < length; i++) {
        if(myArray[i]==toFind) {
            found=true;
        }
    }

    System.out.println(myArray.length);
    System.out.println(found); 
}

I know it's super late, but try Integer[] instead of int[].


It's because Arrays.asList(array) return List<int[]>. array argument is treated as one value you want to wrap (you get list of arrays of ints), not as vararg.

Note that it does work with object types (not primitives):

public boolean contains(final String[] array, final String key) {
    return Arrays.asList(array).contains(key);
}

or even:

public <T>  boolean contains(final T[] array, final T key) {
    return Arrays.asList(array).contains(key);
}

But you cannot have List<int> and autoboxing is not working here.


You can use java.util.Arrays class to transform the array T[?] in a List<T> object with methods like contains:

Arrays.asList(int[] array).contains(int key);

Try Integer.parseInt() to do this.....

public boolean chkInt(final int[] array){
    int key = false;

    for (Integer i : array){


          try{

                   Integer.parseInt(i);
                   key = true;
                   return key;

             }catch(NumberFormatException ex){

                   key = false;

                   return key;

              }


     }
}

A different way:

public boolean contains(final int[] array, final int key) {  
     Arrays.sort(array);  
     return Arrays.binarySearch(array, key) >= 0;  
}  

This modifies the passed-in array. You would have the option to copy the array and work on the original array i.e. int[] sorted = array.clone();
But this is just an example of short code. The runtime is O(NlogN) while your way is O(N)


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift

Examples related to contains

Check if element is in the list (contains) Excel formula to search if all cells in a range read "True", if not, then show "False" How to use regex in XPath "contains" function R - test if first occurrence of string1 is followed by string2 Java List.contains(Object with field value equal to x) Check if list contains element that contains a string and get that element Search for "does-not-contain" on a DataFrame in pandas String contains another two strings Java - Opposite of .contains (does not contain) String contains - ignore case