Implementing GroupBy using Google guava Multimap and Function

Written by

in

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]));
			}
		}
	}
}

Comments

2 responses to “Implementing GroupBy using Google guava Multimap and Function”

  1. Alex Rios Avatar

    Great tip Greg!

    Fill perfectly my needs.

  2. Rafael Avatar
    Rafael

    Great implementation! It worked like a charm!
    Thank you, Greg.

Leave a Reply

Your email address will not be published. Required fields are marked *