How do I add String value in Hash Set if a string contains the same character in upper case and lower case?
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("Abc");
set.add("abc");
System.out.println("Size---"+set.size());
System.out.println(set);
}
OP::
Size---2 [abc, Abc]
Please find following solution. Your original value will remain same.
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
String Str = "Abc";
String Str1 = "abc";
set.add("Abc");
if(!Str.equalsIgnoreCase("abc")) {
set.add("abc");
}
System.out.println("Size---"+set.size());
System.out.println(set);
}
If you want the strings to be added to the hash set case-insensitive, then call toLowerCase()
on strings prior to putting them in:
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("Abc".toLowerCase());
set.add("abc".toLowerCase());
System.out.println("Size---"+set.size());
System.out.println(set);
}
This will produce a set of size 1, containing only "abc".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With