Java, Simplified check if int array contains int

JavaArraysIntContains

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

Here is Java 8 solution

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

Solution 3 - Java

It's because Arrays.asList(array) returns List<int[]>. The array argument is treated as one value you want to wrap (you get a 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.

Solution 4 - Java

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][1]

[1]: http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained "Guava Primitives Explained"

Solution 5 - Java

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)

Solution 6 - Java

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

Solution 7 - Java

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(...)

Solution 8 - Java

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);

Solution 9 - Java

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

Solution 10 - Java

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);

Solution 11 - Java

this worked in java 8

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

Solution 12 - Java

private static void solutions() {
	int[] A = { 1, 5, 10, 20, 40, 80 };
	int[] B = { 6, 7, 20, 80, 100 };
	int[] C = { 3, 4, 15, 20, 30, 70, 80, 120 };

	List<Integer> aList = Arrays.stream(A).boxed().collect(Collectors.toList());

	List<Integer> cList = Arrays.stream(C).boxed().collect(Collectors.toList());
	String s = "";
	for (Integer a : C) {
		if (aList.contains(a) && cList.contains(a)) {
			s = s.concat(String.valueOf(a)).concat("->");
		}
	}
}

Solution 13 - Java

Java 9+

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

Solution 14 - Java

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

Solution 15 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCalebView Question on Stackoverflow
Solution 1 - JavaReimeusView Answer on Stackoverflow
Solution 2 - JavaTriCoreView Answer on Stackoverflow
Solution 3 - JavaTomasz NurkiewiczView Answer on Stackoverflow
Solution 4 - JavaEvertView Answer on Stackoverflow
Solution 5 - JavaCratylusView Answer on Stackoverflow
Solution 6 - JavaWilly WonkaView Answer on Stackoverflow
Solution 7 - JavaJaskeyLamView Answer on Stackoverflow
Solution 8 - JavaHetal RachhView Answer on Stackoverflow
Solution 9 - JavaElavarasan SView Answer on Stackoverflow
Solution 10 - JavaMourad El AomariView Answer on Stackoverflow
Solution 11 - JavaFarhad BaghirovView Answer on Stackoverflow
Solution 12 - JavaKunalView Answer on Stackoverflow
Solution 13 - JavaMahmoud K.View Answer on Stackoverflow
Solution 14 - JavaKaveh GhahremaniView Answer on Stackoverflow
Solution 15 - JavaKumar Vivek MitraView Answer on Stackoverflow