StackTips

Searching arrays and collections in java

nilan avtar

Written by

Nilanchala,  4 min read,  2.51K views, updated on Sept. 17, 2023

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

Beginner's Guide to Java Collections

This course covers the fundamentals of java collections framework covering different data structures in Java to store, group, and retrieve objects.

>> CHECK OUT THE COURSE
nilan avtar

Nilanchala

I'm a blogger, educator and a full stack developer. Mainly focused on Java, Spring and Micro-service architecture. I love to learn, code, make and break things.

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!