Apache Commons


    public String toString() {
            return new ToStringBuilder(this,ToStringStyle.SHORT_PREFIX_STYLE).
            append("offeringPrice", offeringPrice).
              append("productOffering", productOffering).


    public boolean equals(Object obj) {
        if (obj == this) return true;
        if (obj == null) return false;
        if (!(obj instanceof MyObj)) return false;

        MyObj pk = (MyObj) obj;

        return new EqualsBuilder()
        .append(partNumber, pk.partNumber)
        .append(issuer, pk.issuer)

Filtering collections

You can use predicates. It is like having where clause in a collection.

    CollectionUtils.filter(list, PredicateUtils.instanceofPredicate(SomeClass.class));
    CollectionUtils.filter(list, new MyOwnPredicate());
    CollectionUtils.filter(theList, new Predicate(){ 
        public boolean evaluate(Object object) {//If the predicate returns false, remove the element.
                XX product = (XX)object;
                if(...) return true;
                else return false;

Also you can use CollectionUtils.select where we can select all elements from input collection which match the given predicate into an output collection.


Executes the given closure on each element in the collection.

    CollectionUtils.forAllDo(a_list, new MyClosureClass(passing_params));

    CollectionUtils.forAllDo(someList, new Closure(){
        public void execute(Object obj) {
            SomeDto dto = (SomeDto)obj;


Answers true if a predicate is true for at least one element of a collection.

            boolean exist = CollectionUtils.exists(list, new Predicate(){//true if predicate is true
                public boolean evaluate(Object object) {
                    XX product = (XX)object;
                    if(...) return true;
                    else return false;

Mixing Predicates

We can mix predicates together. For instance, OrPredicate gets two predicates and returns true if either of the predicates return true.

    OrPredicate finalPredicate = new OrPredicate(new SomePredicate1(...), new SomePredicate2(...));

Or PredicateUtils.eitherPredicate( p1, p2); creates a new Predicate that returns true if one, but not both, of the specified predicates are true.

There are many other similar methods and combinations.

Copy Beans

  • PropertyUtils.copyProperties(): Copies any property unchanged; handles null, etc.
  • BeanUtils.copyProperties(): copies AND converts similar properties with different types. This might throw NPE due to conversion.


Common Java Cookbook
Apache Commons

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License