Last active
          August 12, 2019 12:57 
        
      - 
      
- 
        Save dougtoppin/d8bdbc5bf693e6121c91 to your computer and use it in GitHub Desktop. 
    Simple example of using an apache commons MultiValueMap to store and retrieve entries with multiple values
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package Multivaluemap1.multivaluemap; | |
| import java.util.Collection; | |
| import java.util.Iterator; | |
| import java.util.LinkedHashMap; | |
| import java.util.LinkedHashSet; | |
| import org.apache.commons.collections4.map.MultiValueMap; | |
| /** | |
| * example of using an apache commons MultiValueMap to store and retrieve | |
| * entries with multiple values per entry | |
| * | |
| * this should produce the following output | |
| key:key1, values=[value1, value2] | |
| value:value1 | |
| value:value2 | |
| key:key2, values=[value3] | |
| value:value3 | |
| * this is dependent on the following: | |
| <dependency> | |
| <groupId>org.apache.commons</groupId> | |
| <artifactId>commons-collections4</artifactId> | |
| <version>4.0</version> | |
| </dependency> | |
| */ | |
| public class Multivaluemap { | |
| public static void main(String[] args) { | |
| @SuppressWarnings("unchecked") | |
| MultiValueMap<String, String> orderedMap = | |
| MultiValueMap.multiValueMap( | |
| new LinkedHashMap<String, Collection<String>>(), | |
| (Class<LinkedHashSet<String>>)(Class<?>)LinkedHashSet.class | |
| ); | |
| orderedMap.put("key1", "value1"); | |
| orderedMap.put("key1", "value2"); | |
| orderedMap.put("key2", "value3"); | |
| Iterator<String> mapIterator = orderedMap.keySet().iterator(); | |
| // iterate over the map | |
| while (mapIterator.hasNext()) { | |
| String key = mapIterator.next(); | |
| System.out.println("key:" + key + ", values=" + orderedMap.get(key)); | |
| Collection<String> values = orderedMap.getCollection(key); | |
| // iterate over the entries for this key in the map | |
| for(Iterator<String> entryIterator = values.iterator(); entryIterator.hasNext();) { | |
| String value = entryIterator.next(); | |
| System.out.println(" value:" + value); | |
| } | |
| } | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment