Check HashSet contains element case insensitive in Java


In this example, we will show you how to check HashSet contains element case insensitive in Java. contains() method of Collection interface returns true if this set contains the specified element. But the problem is contains() method only check the equality of element (case sensitive).

Let’s see all possible cases to check whether HashSet contains a given element or not (case sensitive and insensitive).

Set<String> cars = new HashSet<>();
cars.add("Tata");
cars.add("mAHinDrA");
cars.add("BMW");
cars.add("Maruti Suzuki");

1. Using contains() method

More formally, the contains() method returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

System.out.println(cars.contains("Tata")); // return true

System.out.println(cars.contains("TATA")); // return false

2. Using Java 8

stream() method of Collection interface introduces in JDK 1.8 version to returns a sequential Stream with this collection as its source.

And anyMatch(Predicate<? super T> predicate) returns true if any elements of this stream match the provided predicate.

2.1 Matching equality of element

Below code snippet check the equality of element wheater it is present in HashSet or not with the following conditions:

2.1.1 Case sensitive

boolean containsMyCar = cars.stream().anyMatch("Tata"::equals);
System.out.println(containsMyCar); // return true

boolean containsMyCar2 = cars.stream().anyMatch("bmw"::equals);
System.out.println(containsMyCar2); // return false

2.1.2 Case insensitive

boolean containsMyCar3 = cars.stream().anyMatch("mAHinDrA"::equalsIgnoreCase);
System.out.println(containsMyCar3); // return true

2.1.3 Case insensitive + white spaces

boolean containsMyCar4 = cars.stream().anyMatch("    mAHinDrA   "::equalsIgnoreCase);
System.out.println(containsMyCar4); // return false

2.1.4 Case insensitive + eliminating white spaces

boolean containsMyCar5 = cars.stream().anyMatch("    mAHinDrA   ".trim()::equalsIgnoreCase);
System.out.println(containsMyCar5); // return true

3. Using Java <= 7

All the above possible condition can also be achieved in JDK 1.7 or lesser version. But the only thing is we have to write lengthy code to compare it and there is a slight effect on the performance.

3.1 Enhanced For Loop

Enhanced for loop or for-each loop is introduced in JDK 1.5 version. It provides an alternative approach to traverse the array or collection in Java.

3.1.1 Case sensitive

boolean containsMyCar6 = containMyCarCaseSensitive(cars, "Tata");
System.out.println(containsMyCar6); // return true

private static boolean containMyCarCaseSensitive(Set<String> cars, String myCar) {

	for (String car : cars) {

		if (car.equals(myCar)) {
			return true;
		}
	}
	return false;
}

3.1.2 Case insensitive

boolean containsMyCar7 = containMyCarCaseInSensitive(cars, "mAHinDrA");
System.out.println(containsMyCar7); // return true

private static boolean containMyCarCaseInSensitive(Set<String> cars, String myCar) {

	for (String car : cars) {

		if (car.equalsIgnoreCase(myCar)) {
			return true;
		}
	}
	return false;
}

3.2 Traditional way

Java introduced Iterator interface in JDK 1.2 version. It is applicable for any Collection implemented classes.

For more info check: Java Enumeration, Iterator and ListIterator Example

boolean containsMyCar8 = containMyCarTraditional(cars, "BMW");
System.out.println(containsMyCar8); // return true

private static boolean containMyCarTraditional(Set<String> cars, String myCar) {
	Iterator<String> iterator = cars.iterator();
	while (iterator.hasNext()) {
		if (iterator.next().equals(myCar)) {
			return true;
		}
	}
	return false;
}

Check out all the above code snippet in one place.

HashSetContains.java
package org.websparrow;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetContains {

	public static void main(String[] args) {

		Set<String> cars = new HashSet<>();
		cars.add("Tata");
		cars.add("mAHinDrA");
		cars.add("BMW");
		cars.add("Maruti Suzuki");

		/**
		 * Using Set contains method
		 */

		System.out.println(cars.contains("Tata")); // true

		System.out.println(cars.contains("TATA")); // false

		/**
		 * Using Java 8
		 */

		// matching equality -> Case sensitive
		boolean containsMyCar = cars.stream().anyMatch("Tata"::equals);
		System.out.println(containsMyCar); // true

		boolean containsMyCar2 = cars.stream().anyMatch("bmw"::equals);
		System.out.println(containsMyCar2); // false

		// matching equality -> Case insensitive
		boolean containsMyCar3 = cars.stream().anyMatch("mAHinDrA"::equalsIgnoreCase);
		System.out.println(containsMyCar3); // true

		// matching equality -> Case insensitive + white spaces
		boolean containsMyCar4 = cars.stream().anyMatch("    mAHinDrA   "::equalsIgnoreCase);
		System.out.println(containsMyCar4); // false

		// matching equality -> Case insensitive + eliminating white spaces
		boolean containsMyCar5 = cars.stream().anyMatch("    mAHinDrA   ".trim()::equalsIgnoreCase);
		System.out.println(containsMyCar5); // true

		/**
		 * Using Java <= 7
		 */

		// Enhanced for loop

		boolean containsMyCar6 = containMyCarCaseSensitive(cars, "Tata");
		System.out.println(containsMyCar6); // true

		boolean containsMyCar7 = containMyCarCaseInSensitive(cars, "mAHinDrA");
		System.out.println(containsMyCar7); // true

		// Traditional way
		boolean containsMyCar8 = containMyCarTraditional(cars, "BMW");
		System.out.println(containsMyCar8); // true
	}

	private static boolean containMyCarCaseSensitive(Set<String> cars, String myCar) {

		for (String car : cars) {

			if (car.equals(myCar)) {
				return true;
			}
		}
		return false;
	}

	private static boolean containMyCarCaseInSensitive(Set<String> cars, String myCar) {

		for (String car : cars) {

			if (car.equalsIgnoreCase(myCar)) {
				return true;
			}
		}
		return false;
	}

	private static boolean containMyCarTraditional(Set<String> cars, String myCar) {
		Iterator<String> iterator = cars.iterator();
		while (iterator.hasNext()) {
			if (iterator.next().equals(myCar)) {
				return true;
			}
		}
		return false;
	}
}

Output

true
false
true
false
true
false
true
true
true
true

References

  1. Java 8 Stream Interface
  2. Java 8 Collection.stream()
  3. Java 8 Stream anyMatch()

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.