title: How to write a generic isEmpty method which can check for null, empty?
body: <p>I am writing a utility method which can check for empty and null string, or collection or an object or any general types -</p>
  
  <pre><code>public static boolean isEmpty(Object obj) {
      if (obj == null)
          return true;
      if (obj instanceof Collection)
          return ((Collection&lt;?&gt;) obj).size() == 0;
  
      // is below line expensive?
      final String s = String.valueOf(obj).trim();
  
      return s.length() == 0 || s.equalsIgnoreCase("null");
  }
  </code></pre>
  
  <p>How can I make my above method efficient, since above <code>isEmpty</code> method will be called multiple times from the application which is very performance critical?</p>
  
  <p>I am suspecting below line will be expensive because of heavy toString methods and it will create temporary garbage as well that might cause GC and slow down the performance?</p>
  
  <pre><code>final String s = String.valueOf(obj).trim();
  </code></pre>
  
  <p><strong>Update:-</strong></p>
  
  <p>I have separated isEmpty method for each type now. Below is what I got after simplifying the above isEmpty method.</p>
  
  <pre><code>public static boolean isEmpty(Object obj) {
      if (obj == null) {
          return true;
      }
      return false;
  }
  
  public static boolean isEmpty(Collection&lt;?&gt; value) {
      if (value == null || value.isEmpty()) {
          return true;
      }
      return false;
  }
  
  public static boolean isEmpty(String value) {
      if (value == null || value.isEmpty()) {
          return true;
      }
      return false;
  }
  </code></pre>
  
  <p><strong>Update 2:-</strong></p>
  
  <p>If I need to check for map null or empty, should I keep both collection isEmpty and Map isEmpty method both or Collection isEmpty method will be fine for that?</p>
  
  <pre><code>public static void main(String[] args) {
  
      Map&lt;String, String&gt; hello = new HashMap&lt;String, String&gt;();
      System.out.println(isEmpty(hello));
  
      Map&lt;String, HashMap&lt;Integer, String&gt;&gt; primary = new HashMap&lt;String, HashMap&lt;Integer, String&gt;&gt;();
      System.out.println(isEmpty(primary));
  
  }
  
  public static boolean isEmpty(Collection&lt;?&gt; value) {
      return value == null || value.isEmpty();
  }
  
  public static boolean isEmpty(Map&lt;?, ?&gt; value) {
      return value == null || value.isEmpty();
  }
  </code></pre>