JavaRanch Home    
 
This page:         last edited 30 March 2012         What's Changed?         Edit

Learn Groovy   

Lots of Groovy examples can be found at the Groovy home page http://groovy.codehaus.org/, for example

Questions about Groovy can be asked in the JavaRanch Groovy forum.


An example

To start with, here are two versions of a short Groovy program that solves the first problem of Project Euler : If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

def getSumOfMultiples = {def numbers, int max ->
    def allProducts = new TreeSet()
    numbers.each{
        int product = it 
        while (product<=max){
            allProducts << product
            product += it
        }
    }
    return allProducts.sum()
}

def getSumOfMultiples = {def numbers, int max ->
    (1..max).findAll{index->
        numbers.find{num->(index%num==0)}
    }.sum()
}

Both would be called using println getSumOfMultiples([3,5], 1000)


CategoryLearnSomethingNew GroovyFaq

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton