Month: December 2010

  • Implementing GroupBy using Google guava Multimap and Function

    This is one way of creating a group by like functionality for collections using google guava Multimap and Function.

    Code is straight forward we simply use the index method of the Multimap to group our data by, in here we use our 2 column to group it by the department.

    Sample output

    key = Dev
      1 : Greg
      3 : Roman
    key = Support
      2 : Leo
      4 : Jobby
    

    Code

    package com.gregbugaj.guava;
    
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.List;
    
    import com.google.common.base.Function;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Multimap;
    import com.google.common.collect.Multimaps;
    
    public class GroupByMultimap {
    	public static void main(String[] args) {
    		Object[] o1 = new Object[] { 1, "Greg", "Dev" };
    		Object[] o2 = new Object[] { 2, "Leo", "Support" };
    		Object[] o3 = new Object[] { 3, "Roman", "Dev" };
    		Object[] o4 = new Object[] { 4, "Jobby", "Support" };
    
    		List rows = Lists.newArrayList(o1, o2, o3, o4);
    		Multimap grouped = Multimaps.index(rows,
    				new Function() {
    					@Override
    					public String apply(Object[] item) {
    						return (String) item[2];
    					}
    				});
    
    		Iterator keyIterator = grouped.asMap().keySet().iterator();
    		while (keyIterator.hasNext()) {
    			String key = keyIterator.next();
    			System.out.println("key = " + key);
    			Collection dataRows = grouped.get(key);
    			for (Object[] o : dataRows) {
    				System.out.println(String.format("  %d : %s", o[0], o[1]));
    			}
    		}
    	}
    }