Skip to content

Yet Another Useful Groovy Snippet

The question was: “What’s the cleanest way to add variable size String of spaces?”

Here’s my snippet:

def pad = { what, repeat -> what * repeat }

(0..9).each {
  println "${pad(' ', it)}Hello!" 
  }

This gives:

Hello!
 Hello!
  Hello!
   Hello!
    Hello!
     Hello!
      Hello!
       Hello!
        Hello!
         Hello!

This makes use of the fact that you can just multiply strings in Groovy.

Quite neat, IMHO!

Groovy has a built-in solution, which has slightly different behaviour:

(0..9).each {
  println "hello".padLeft(it, '_')
}

Gives:

hello
hello
hello
hello
hello
hello
_hello
__hello
___hello
____hello

Unsurprisingly, a version making use of Apache Commons Lang StringUtils behaves exactly the same way:

import static org.apache.commons.lang.StringUtils.* 

(0..9).each {
  println leftPad('hello', it, '_')
}

Just for completeness: there’s java.util.Formatter but unlike with C’s printf function, one cannot specify a field’s width via a variable.

Tags: ,

C, Java Enterprise Edition, JEE, J2EE, JBoss, Application Server, Glassfish, JavaServer Pages, JSP, Tag Libraries, Servlets, Enterprise Java Beans, EJB, Java Messaging Service JMS, BEA Weblogic, JBoss, Application Servers, Spring Framework, Groovy, Grails, Griffon, GPars, GAnt, Spock, Gradle, Seam, Open Source, Service Oriented Architectures, SOA, Java 2 Standard Edition, J2SE, Eclipse, Intellij, Oracle Service Bus, OSB