Friday, October 30, 2015

TreeSet Case Insensitive Check




As we know that TreeSet by default store the unique value it doesn’t check case of the value that is being added.
For example if we have a set instance set1 of string type and add value like as follows.
set1.add(“a”);
set1.add(“A”);
Now if we check the size of set1 , it will give size 2 because ASCII value of  ‘a’ & ‘A’ is different, as well as equality check of both value will return false so set1 will add both the value.
It is not amazing it is the default nature of set.
Suppose we have a scenario that set should ignore case sensitive value  and when user add two value like ‘a’ & ‘A’ it should only store one value.
  See the below mentioned example which solve the case sensitive problem.
Set<String> set1=new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
            set1.add("a");
            set1.add("A");
           
            System.out.println(set1.size());
            System.out.println(set1);

Output :
1
[a]

No comments:

Post a Comment

Spring Boot Config Server and Config Client.

 In Spring cloud config we can externalise our configuration files to some repository like GIT HUT, Amazon S3 etc. Benefit of externalising ...