• Technical
  • How to convert ResultSet into ListMultiMap in Java

How to convert ResultSet into ListMultiMap in Java

Hi guys,

In few of my previous posts I mentioned about an API from Google called Guava. This API has a class called ListMultiMap. Today I am going to show you how you can use ListMultiMap to use the database ResultSet more efficiently.

This will give developers a clear visibility regarding the column names and the values associated with them and also will help to retrieve values when performing iteration.


import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;

 * This class converts ResultSet into ListMultiMap
 * @author Nitesh Apte
 * @license GPL
public class ResultSetToListMultiMap {

   * Converts ResultSet to ListMultiMap
   * @param resultSet
   * @return
  public ListMultimap<String, String> resultSetToListMultiMap(ResultSet resultSet) {
    ListMultimap<String, String> multimap = null;
      multimap = ArrayListMultimap.create();

      ResultSetMetaData rsmd = resultSet.getMetaData();

      int columnCount = rsmd.getColumnCount();
      List<String> s1 = new ArrayList<String>();
      for (int i = 1; i < columnCount+1; i++ ) {
      while (resultSet.next()) {      
        for(int i=0;i<s1.size();i++) {
          multimap.put(s1.get(i), resultSet.getString(s1.get(i)));
    } catch (Exception e) { 
    return multimap;

I understand, something like this can be achieved using HashMap but I will suggest to use ListMultiMap as it is more memory efficient.

That’s it for today guys.

Critics/suggestion are very much welcome.

Have a nice day ahead.

2,857 total views, 1 views today

This entry was posted in Technical

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.

Follow Me