Apache Java Snippits

From Kb

Jump to: navigation, search

Contact Article Author | Blog of Article Author | FirstPartners.net Home | LinkedIn profile of Author

Contents

Apache Commons String Manipulation

Easy toString() method using Apache Commons ToStringBuilder

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
 
    public String toString() {
        return  ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE);
    }

To get the above files via maven, add the following to pom.xml

<dependency>
      	<groupId>commons-lang</groupId>
  	<artifactId>commons-lang</artifactId>
      	<version>2.3</version>
  </dependency>

Loop through a list and print the values

Iterator li = l.iterator();
        while (li.hasNext()){
            log.debug(ReflectionToStringBuilder.reflectionToString(li.next(),       ToStringStyle.DEFAULT_STYLE));
        }

Find and Replace in String

Apache StringUtils Javadoc

import org.apache.commons.lang.StringUtils;
 
....
//This will remove all occurances of left bracket
StringUtils.replace(in,"("," ");

Using Apache Commons Collections

Apache Commons Collections Javadoc

Ensure that 2 lists do not have any common values

import org.apache.commons.collections.ListUtils;
 
        List commonItems= ListUtils.intersection(list1,list2);
        assertEquals (interSection.size()==0); //for JUnit test, but production code is similar
Personal tools