Thursday, 26 September 2013

Java: Code to unquote string using Regex


str="\"hello\"" // or "'hello'"

public static unquote(String str)
{
        str = str.trim();
if (str.startsWith("'") && str.endsWith("'"))
{
    str = match(str, "(?<=').*(?=')");
}
else if (str.startsWith("\"") && str.endsWith("\""))
{
         str = match(str, "(?<=\").*(?=\")");
}
}

//matches the pattern
private static String match(final String string, final String regex)
{
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
matcher.find();
return matcher.group(); 
}

[Shared Webinar] Getting Started with ElasticSearch

Click on the Below Image and fill in details to watch the Webinar


Saturday, 21 September 2013

Quick Notes : Practical usage of collections

Different Types of Collections and when to Use them

Set

HashSet : 

  • When you want unique set to objects. 
  • Make sure equals and hashcode is implemented.
  • This does not maintain the order of object addition. As the name says it is Hashed

TreeSet:
  • You can have the list ordered the way you want, by passing in a comparator.
  • Example: new TreeSet(String.CASE_INSENSITIVE_ORDER)
  • It automatically orders the objects that you add accordingly

LinkedHashSet
  • This gives us the flexibility of HashSet (uniqueness) and 
  • also maintains the insertion-order of objects

Map

HashMap :
  • Easier way of holding Key Value Pair
  • Does not maintain the insertion-order (Hashed)
TreeMap:
  • Sorted Map, Sorting of keys determined by the comparator in the constructor
  • Quickly create a map of case insensitive keys as follows
    new TreeMap(String.CASE_INSENSITIVE_ORDER)
  • Throws a NullPointerException if you use get without a null check.
    treemap.get(null), so better add a null check before invoking get()
LinkedHashMap:
  • Extends HashMap. But, preserves of the insertion order

List:

ArrayList:
  • Quicker way of maintaining a list of objects
  • can add duplicate values.
  • It is advisable to use this collection if we expect more number of gets() than add() or set()
LinkedList:
  • Performs better when you have more additions and insertions than searching the list