Java find elem in array

Java find elem in array

  • Find the Missing Number
  • Find the first repeating element in an array of integers
  • Find the missing and repeating number
  • Count 1’s in a sorted binary array
  • Two elements whose sum is closest to zero
  • Find a pair with the given difference
  • Kth smallest element in a row-wise and column-wise sorted 2D array
  • Find common elements in three sorted arrays
  • Ceiling in a sorted array
  • Floor in a Sorted Array
  • Find the maximum element in an array which is first increasing and then decreasing
  • Given Array of size n and a number k, find all elements that appear more than n/k times
  • Find all triplets with zero sum
  • Find the element before which all the elements are smaller than it, and after which all are greater
  • Find the largest pair sum in an unsorted array
  • K’th Smallest/Largest Element in Unsorted Array
  • Search an element in a sorted and rotated Array
  • Find the Minimum element in a Sorted and Rotated Array
  • Find a Fixed Point (Value equal to index) in a given array
  • Find the k most frequent words from a file
  • Find k closest elements to a given value
  • Given a sorted array and a number x, find the pair in array whose sum is closest to x
  • Find the closest pair from two sorted arrays
  • Find three closest elements from given three sorted arrays
  • Binary Search for Rational Numbers without using floating point arithmetic
Читайте также:  Множества в питоне определение

Источник

Find element in array

In this example we will search for specified object in a given array while using java, guava and apache commons. Since we are huge fans of the Minnesota Vikings, not, we will highlight losings seasons and check if a specified value exists.

Straight up Java

With straight up java, there are multiple ways to find an element in an array. We will first iterate over an array with a java 5 for each loop comparing each element to 1962. If 1962 is found, we will set the losingSeason boolean variable to false and proceed to break the loop.

Loop

@Test public void search_array_java ()  Integer[] vikQueensLosingSeasons =  1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985>; boolean losingSeason = false; for (Integer number : vikQueensLosingSeasons)  if (number.equals(1962))  losingSeason = true; break; > > assertTrue(losingSeason); >

List contains

Similar to how we find an element in a collection we will convert the array to a list and then call Lists.contains to check if the list contains the specified element.

@Test public void search_array_java_with_list_contains_with_list_contains ()  Integer[] vikQueensLosingSeasons =  1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985>; boolean hadALosingSeason = Arrays .asList(vikQueensLosingSeasons) .contains(new Integer(1962)); assertTrue(hadALosingSeason); >

Another technique is to use Arrays.binarySearch to find an element in an array by using the binary search algorithm. When using this technique, you must sort array in ascending order according to the natural ordering of its elements.

@Test public void array_contains_element_java_binary_search ()  Integer[] vikQueensLosingSeasons =  1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985>; Arrays.sort(vikQueensLosingSeasons); int elementPosition = Arrays.binarySearch(vikQueensLosingSeasons, 1962); assertTrue(elementPosition >= 0); >

Java 8

Using java 8 we will build a stream from an array using Arrays.stream, them filter the stream with criteria to find an element in an array. Next we will call the Stream.findAny method which will return an Optional describing the element if found otherwise an empty Optional if the stream is empty.

@Test public void array_contains_element_java8 ()  Integer[] vikQueensLosingSeasons =  1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985>; java.util.OptionalInteger> yearExists = Arrays.stream(vikQueensLosingSeasons) .filter(p -> p == 1972) .findAny(); assertTrue(yearExists.isPresent()); >

Google Guava

Primitive contains

Ints is class in the guava library that contains a series of static methods pertaining to int primitives. In the example below, we will call Int.contains on the vikQueensLosingSeasons to verify that 1972 exists.

@Test public void array_contains_element_java_with_guava ()  int[] vikQueensLosingSeasons =  1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985>; boolean yearExists = Ints.contains(vikQueensLosingSeasons, 1972); assertTrue(yearExists); >

Iterator.tryfind w/ predicate

Guava Iterables utilty class provides Iterables.tryFind method which returns a guava Optional class containing the first element in the array that satisified the given predicate. If an element doesn’t exists it will return an empty Optional.

@Test public void find_element_in_array_java_with_guava()  Integer[] vikQueensLosingSeasons =  1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985 >; OptionalInteger> contains = Iterators.tryFind( Iterators.forArray(vikQueensLosingSeasons), new PredicateInteger>()  public boolean apply(Integer input)  if (input == 1962)  return true; > else  return false; > > >); assertTrue(contains.isPresent()); assertEquals(new Integer(1962), contains.get()); >

Apache Commons

Apache commons ArrayUtils class provides operations for dealing with primitive arrays. The ArrayUtils.contains method will check if the value is in the given array.

@Test public void array_contains_element_java_with_apache_commons ()  int[] vikQueensLosingSeasons =  1962, 1967, 1984, 2011, 1966, 1963, 1982, 2001, 1990, 2002, 2006, 2010, 1965, 1972, 1979, 1981, 1985>; boolean losingSeason = ArrayUtils.contains(vikQueensLosingSeasons, 1962); assertTrue(losingSeason); >

Find element in array posted by Justin Musgrove on 14 January 2014

Tagged: java and java-arrays

Источник

4 Ways to Search Java Array to Find an Element or Object — Tutorial Example

Searching in Java Array sounds familiar? should be, because it’s one of the frequently used operations in Java programming. The array is an index-based data structure that is used to store elements but unlike Collection classes like ArrayList or HashSet which has contains() method, the array in Java doesn’t have any method to check whether an element is inside an array or not. Java programming language provides several ways to search any element in the Java array.

In this Java tutorial, we will see 4 examples of searching Array in Java for an element or object. Every example is different than others and some of them are faster and others are slow but take less memory.

These techniques are also valid for different types of arrays e.g. primitive and object arrays. I always suggest preferring List over Array until you need every bit of performance from your Java application, it is not only convenient to work but also more extensible.

4 ways to search array in Java — Examples

1. Searching Array by converting Array to ArrayList in Java

How to search Object in a Java array with example

ArrayList in Java has a convenient method called contains() which returns true if the object passed to it are inside ArrayList. by converting an array into ArrayList in Java we can easily use this option for searching any element in Java array.

2. Search Java array by converting Array to HashSet

Just like we can leverage ArrayList’s contains method we can also use HashSet contains () method which has O(1) response time for search. So if you need constant search time to find an element in array, consider converting your Array into HashSet in Java. see the code section for complete example of searching elements in Java array using HashSet’s contains() method.

3. Searching Java Array using Arrays.binarySearch()

Binary Search is another faster way of searching elements in Java array but it requires array to be sorted while earlier examples of finding elements on Array can be used with both sorted and unsorted array . java.util.Arrays class provides both sort() and binarySearch() for first sorting an array and than performing binary search on it. Arrays.binarySearch() method returns >=0 if it finds elements in Array. see code section for full code example of binarySearch in Java array.

4. Finding element in Java array using the foreach loop

This is a plain, old, brute force way of searching elements on array in Java or any other programming language like C or C++. You iterate through array comparing each element to input and returning true once you have matched. this is a completely linear operation and if your array is large and input is at the rear end it can take a long time to search the array. O(n) operations are also not preferred.

One more way of searching an element in the array is by using the Apache commons ArrayUtils class. ArrayUtils class provide several overloaded method which accept array and item to be found e.g. int array, long array or Object array and returns true or false if Array contains that element.

This requires just one line of code but you need to include Apache commons library in your classpath. See How to find index of element in Java array for complete code example in Java.

Code Example of Searching Java array to find elements

here is complete code examples of all 4 ways of searching java arrays. you can use any way as per your need but HashSet() is best in terms of speed and consider using that.

import java.util.Arrays ;
import java.util.HashSet ;
import java.util.List ;
import java.util.Set ;

public class SearchTest

public static void main ( String args [])

//searching element on unsorted Java array
//searching java array using ArrayList
List < Integer > array = Arrays. asList ( 1 , 3 , 5 , 2 , 4 ) ;
if ( array. contains ( 3 )) <
System. out . println ( «Element found inside Java array using» +

«ArrayList contains() method» ) ;
> ;

Set < Integer > arraySet = new HashSet < Integer > ( array ) ;

if ( arraySet. contains ( 3 )) <
System. out . println ( «Element found on Java array using» +

//searching element on sorted Java array
//unsorted String array
String [] cities = new String [] < "Washington" , "London" , "Paris" , "NewYork" >;

//sorting array in java
Arrays. sort ( cities ) ;

//searching on sorted array in java using Arrays binarySearch() method
if ( Arrays. binarySearch ( cities, «Paris» ) > = 0 ) <
System. out . println ( «Element found on sorted String Java» +

«array using binary search» ) ;
>

//plain old for loop for searching elements in Java array
String input = «London» ;
for ( String city: cities ) <
if ( city. equals ( input )) <
System. out . println ( «Found elements in Java array using for loop» ) ;
>
>

That’s all on How to search an element inside an Array in Java. You can use any of the above methods to search your Java array for any object. Remember that Collection classes like HashSet and ArrayList use equals() method to determine if two objects are equal or not. So if your testing for custom objects make sure you override the equals and hashCode method and follow equals and hashCode contract in Java.

Источник

Оцените статью