- Check value in set java
- Method Summary
- Unmodifiable Sets
- Check HashSet contains element case insensitive in Java
- 1. Using contains() method
- 2. Using Java 8
- 2.1 Matching equality of element
- 3. Using Java 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 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 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. boolean containsMyCar8 = containMyCarTraditional(cars, "BMW"); System.out.println(containsMyCar8); // return true private static boolean containMyCarTraditional(Set cars, String myCar) < Iteratoriterator = cars.iterator(); while (iterator.hasNext()) < if (iterator.next().equals(myCar)) < return true; >> return false; > Check out all the above code snippet in one place. package org.websparrow; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class HashSetContains < public static void main(String[] args) < Setcars = 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 private static boolean containMyCarCaseSensitive(Set cars, String myCar) < for (String car : cars) < if (car.equals(myCar)) < return true; >> return false; > private static boolean containMyCarCaseInSensitive(Set cars, String myCar) < for (String car : cars) < if (car.equalsIgnoreCase(myCar)) < return true; >> return false; > private static boolean containMyCarTraditional(Set cars, String myCar) < Iteratoriterator = cars.iterator(); while (iterator.hasNext()) < if (iterator.next().equals(myCar)) < return true; >> return false; > > true false true false true false true true true true References Источник
- 3.1 Enhanced For Loop
- 3.2 Traditional way
- References
Check value in set java
Interface Set
- Type Parameters: E — the type of elements maintained by this set All Superinterfaces: Collection, IterableAll Known Subinterfaces: NavigableSet, SortedSetAll Known Implementing Classes: AbstractSet, ConcurrentHashMap.KeySetView, ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet, HashSet, JobStateReasons, LinkedHashSet, TreeSet
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2) , and at most one null element. As implied by its name, this interface models the mathematical set abstraction. The Set interface places additional stipulations, beyond those inherited from the Collection interface, on the contracts of all constructors and on the contracts of the add, equals and hashCode methods. Declarations for other inherited methods are also included here for convenience. (The specifications accompanying these declarations have been tailored to the Set interface, but they do not contain any additional stipulations.) The additional stipulation on constructors is, not surprisingly, that all constructors must create a set that contains no duplicate elements (as defined above). Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element. Some set implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the set may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface. This interface is a member of the Java Collections Framework.
Method Summary
Adds all of the elements in the specified collection to this set if they’re not already present (optional operation).
Interface Set
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2) , and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
The Set interface places additional stipulations, beyond those inherited from the Collection interface, on the contracts of all constructors and on the contracts of the add , equals and hashCode methods. Declarations for other inherited methods are also included here for convenience. (The specifications accompanying these declarations have been tailored to the Set interface, but they do not contain any additional stipulations.)
The additional stipulation on constructors is, not surprisingly, that all constructors must create a set that contains no duplicate elements (as defined above).
Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.
Some set implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the set may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.
Unmodifiable Sets
- They are unmodifiable. Elements cannot be added or removed. Calling any mutator method on the Set will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the Set to behave inconsistently or its contents to appear to change.
- They disallow null elements. Attempts to create them with null elements result in NullPointerException .
- They are serializable if all elements are serializable.
- They reject duplicate elements at creation time. Duplicate elements passed to a static factory method result in IllegalArgumentException .
- The iteration order of set elements is unspecified and is subject to change.
- They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
- They are serialized as specified on the Serialized Form page.
This interface is a member of the Java Collections Framework.
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 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(Predicatesuper 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
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 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 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.
boolean containsMyCar8 = containMyCarTraditional(cars, "BMW"); System.out.println(containsMyCar8); // return true private static boolean containMyCarTraditional(Set cars, String myCar) < Iteratoriterator = cars.iterator(); while (iterator.hasNext()) < if (iterator.next().equals(myCar)) < return true; >> return false; >
Check out all the above code snippet in one place.
package org.websparrow; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class HashSetContains < public static void main(String[] args) < Setcars = 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 private static boolean containMyCarCaseSensitive(Set cars, String myCar) < for (String car : cars) < if (car.equals(myCar)) < return true; >> return false; > private static boolean containMyCarCaseInSensitive(Set cars, String myCar) < for (String car : cars) < if (car.equalsIgnoreCase(myCar)) < return true; >> return false; > private static boolean containMyCarTraditional(Set cars, String myCar) < Iteratoriterator = cars.iterator(); while (iterator.hasNext()) < if (iterator.next().equals(myCar)) < return true; >> return false; > >
true false true false true false true true true true