пятница, 20 января 2012 г.

Case insensitive to HashSet

Problem:
Case insensitive to HashSet

     You need to that the HashSet add elements without case insensitive. This can be completed in two ways:

1. First solution:

     Use TreeSet

Result:

      Sokrted collection TreeSet (since TreeSet automatically sorts the elements)

Java code:

     Set set = new TreeSet(String.CASE_INSENSITIVE_ORDER);
     String s1 = "TO";
     String s2 = "to";
     set.add(s1);
     set.add(s2);
     System.out.println(set.toString());

/////////////////////////////////////////////////////////////
2. Second solution:
     Use LinkedHashMap

Result:

     Collection with elements as they was added

Java code:

     Map map = new LinkedHashMap();
     String s1 = "TO DO";
     String s2 = "To do";
     map.put(s1.toUpperCase(), s2);
     map.put(s2.toUpperCase(), s2);
     for (Map.Entry entry : map.entrySet()){
     System.out.println("key = " + entry.getKey());
     System.out.println("value = " + entry.getValue());
      }

Комментариев нет:

Отправить комментарий