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.

ResultSetToListMultiMap.java

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;
    try{
      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++ ) {
        s1.add(rsmd.getColumnName(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) { 
      e.printStackTrace();  
    }  
    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.

Loading