Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add String value in Hash Set if a string contains the same character in upper case and lower case?

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]

like image 475
Krunal Patel Avatar asked Feb 13 '23 19:02

Krunal Patel


2 Answers

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);

}
like image 197
shrey Avatar answered Feb 15 '23 09:02

shrey


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".

like image 38
FrobberOfBits Avatar answered Feb 15 '23 08:02

FrobberOfBits