user10525165
user10525165

Reputation: 1

How to create a map having multiple values mapped to same key out of List<Map<String,Object>?

I have a data extracted in a List of Map which has multiple values associated to same key. Now I need to extract key value pairs from dbvalues(which is a list of map) and put it into Map> But how would I extract data from the list of map so that I can put into this map?

List<Map<String, Object>> dbvalues = new ArrayList<Map<String, Object>>();
dbvalues = JdbcTemplate.queryForList(sql_query);
Map<String, List<String>> test = new HashMap<String, List<String>>();

expected resulting Map - 
key1 - x,y,z
key2 - a,b,c...and so on

Upvotes: 0

Views: 986

Answers (2)

Lucas Oliveira
Lucas Oliveira

Reputation: 3477

You may use Guava's com.google.common.collect.ListMultimap

from the com.google.common.collect.Multimap's javadoc:

It is a collection that maps keys to values, similar to java.util.Map, but in which each key may be associated with multiple values. You can visualize the contents of a multimap as a map from keys to non empty collections of values.

The most straight-forward way to create a Multimap is using MultimapBuilder, which allows you to configure how your keys and values should be represented. For example:

// creates a ListMultimap wich will behave like an Map<String,ArrayList<Object>>
ListMultimap<String, Object> listMultimap = MultimapBuilder.hashKeys().arrayListValues().build();

Once you have a multimap, you can just put the key, value pairs in for loops:

for(final Map<String,Object> map : dbvalues){
    for(final Entry<String,Object> entry : map.entrySet()){
        listMultimap.put( entry.getKey(), entry.getValue() );
    }
}

For a more info on Multimaps: https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap

Upvotes: 0

Mark
Mark

Reputation: 5239

You can loop through the .entrySet() of the Map<String, List<String>>, print each key and join the values (the List<String>) with a ,

Map<String, List<String>> test = new HashMap<>();

// Fill with sample data
test.put("key1", Arrays.asList("x", "y", "z"));
test.put("key2", Arrays.asList("a", "b", "c"));

// Print the contents
for (Entry<String, List<String>> e : test.entrySet()) {
    System.out.println(e.getKey() + " - " + String.join(",", e.getValue()));
}

// This prints:
// key1 - x,y,z
// key2 - a,b,c

Upvotes: 2

Related Questions