StackTips

Searching arrays and collections in java

Arrays and Collection class provides methods that allows to search a specific element in the list. Things to know while searching a collection or an array;

  • Search is performed using binarySearch() method
  • If the element found in the collection or array it returns the element index. If the index is a non negative integer greater than zero then element found.
  • The collection array needs to be sorted before performing search algorithm. If the collection is not sorted then the result will be unpredictable. Note that the sorting should be performed in natural order.
  • If the sorting is not made in natural order, and performed using Comparator, then searching should be performed using same Comparator.

Example of searching Array/Collection in java

package com.java.test;

import java.util.Arrays;
import java.util.Comparator;

public class SearchObjectArray {

	public static void main(String[] args) {
		String[] names = { "Neel", "Clay", "Adams", "Joseph", "Jack" };

		// sorting array
		Arrays.sort(names);

		// printing after sort
		for (String name : names) {
			System.out.println(name);
		}

		// Search result for "one"
		System.out.println("Search Adams=" + Arrays.binarySearch(names, "Adams"));

		System.out.println("======================================");

		// reverse sorting
		ReverseSortComparator reSort = new ReverseSortComparator();
		Arrays.sort(names, reSort);
		for (String name : names) {
			System.out.println(name);
		}

		// Search result for "one"
		System.out.println("Search Adams=" + Arrays.binarySearch(names, "Adams", reSort));
	}

	static class ReverseSortComparator implements Comparator {

		public int compare(String a, String b) {
			return b.compareTo(a);
		}

	}

}

Output of the above code is

Searching arrays and collections

nilanchala avtar

Nilanchala Panigrahy

A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (goo.gl/qUZ0XV3)