org.apache.commons.collections.MultiMap类的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(12.1k)|赞(0)|评价(0)|浏览(112)

本文整理了Java中org.apache.commons.collections.MultiMap类的一些代码示例,展示了MultiMap类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MultiMap类的具体详情如下:
包路径:org.apache.commons.collections.MultiMap
类名称:MultiMap

MultiMap介绍

[英]Defines a map that holds a collection of values against each key.

A MultiMap is a Map with slightly different semantics. Putting a value into the map will add the value to a Collection at that key. Getting a value will return a Collection, holding all the values put to that key.

For example:

MultiMap mhm = new MultiHashMap(); 
mhm.put(key, "A"); 
mhm.put(key, "B"); 
mhm.put(key, "C"); 
Collection coll = (Collection) mhm.get(key);

coll will be a collection containing "A", "B", "C".

NOTE: Additional methods were added to this interface in Commons Collections 3.1. These were added solely for documentation purposes and do not change the interface as they were defined in the superinterface Map anyway.
[中]定义一个映射,该映射针对每个键保存一组值。
MultiMap是一个语义稍有不同的映射。将值放入地图将在该键处向集合添加值。获取一个值将返回一个集合,其中包含所有放入该键的值。
例如:

MultiMap mhm = new MultiHashMap(); 
mhm.put(key, "A"); 
mhm.put(key, "B"); 
mhm.put(key, "C"); 
Collection coll = (Collection) mhm.get(key);

coll将是一个包含“a”、“B”、“C”的集合。
注:Commons Collections 3.1中向该接口添加了其他方法。这些仅为文档目的而添加,不会更改superinterfaceMap中定义的接口。

代码示例

代码示例来源:origin: openmrs/openmrs-core

private MultiMap getAsPropertiesKeyValueMultiMap(List<String> fileLines) {
  MultiMap multiMap = new MultiValueMap();
  for (String line : fileLines) {
    if (isCorectKeyValueLine(line)) {
      Map.Entry<String, String> tuple = extractKeyValue(line);
      multiMap.put(tuple.getKey(), tuple.getValue());
    }
  }
  return multiMap;
}

代码示例来源:origin: apache/flume

int total = 0;
int count = 0;
MultiMap transactionMap = new MultiValueMap();
 Set<Long> eventPointers = inflightPuts.get(txnID);
 for (Long eventPointer : eventPointers) {
  transactionMap.put(txnID, FlumeEventPointer.fromLong(eventPointer));
     putCount++;
     ptr = new FlumeEventPointer(fileId, offset);
     transactionMap.put(trans, ptr);
    } else if (type == TransactionEventRecord.Type.TAKE.get()) {
     takeCount++;
     Take take = (Take) record;
     ptr = new FlumeEventPointer(take.getFileID(), take.getOffset());
     transactionMap.put(trans, ptr);
    } else if (type == TransactionEventRecord.Type.ROLLBACK.get()) {
     rollbackCount++;
     transactionMap.remove(trans);
    } else if (type == TransactionEventRecord.Type.COMMIT.get()) {
     commitCount++;
     @SuppressWarnings("unchecked")
     Collection<FlumeEventPointer> pointers =
       (Collection<FlumeEventPointer>) transactionMap.remove(trans);
     if (((Commit) record).getType() == TransactionEventRecord.Type.TAKE.get()) {
      if (inflightTakes.containsKey(trans)) {

代码示例来源:origin: openmrs/openmrs-core

private List<String> filterKeysWithMultipleValues(MultiMap keyValuesMap) {
  List<String> result = new ArrayList<>();
  for (Object entryObject : keyValuesMap.entrySet()) {
    // apache commons multimap in version 3.* do not use generics (
    // version 4.0 has)
    @SuppressWarnings("unchecked")
    Map.Entry<String, Collection<?>> mapEntry = (Entry<String, Collection<?>>) entryObject;
    if (mapEntry.getValue().size() > 1) {
      result.add(mapEntry.getKey());
    }
  }
  return result;
}

代码示例来源:origin: commons-collections/commons-collections

public void testPutAll_Map1() {
  MultiMap original = new MultiValueMap();
  original.put("key", "object1");
  original.put("key", "object2");
  MultiValueMap test = new MultiValueMap();
  test.put("keyA", "objectA");
  test.put("key", "object0");
  test.putAll(original);
  assertEquals(2, test.size());
  assertEquals(4, test.totalSize());
  assertEquals(1, test.getCollection("keyA").size());
  assertEquals(3, test.getCollection("key").size());
  assertEquals(true, test.containsValue("objectA"));
  assertEquals(true, test.containsValue("object0"));
  assertEquals(true, test.containsValue("object1"));
  assertEquals(true, test.containsValue("object2"));
}

代码示例来源:origin: org.hibernate/hibernate-tools

MultiValueMap result = new MultiValueMap();
MetaAttributeHelper.copyMultiMap(result, specific);
  for (Iterator<?> iter = general.keySet().iterator();iter.hasNext();) {
    Object key = iter.next();
    if (!specific.containsKey(key) ) {
      Collection<?> ml = (Collection<?>)general.get(key);
      for (Iterator<?> iterator = ml.iterator(); iterator.hasNext();) {
        SimpleMetaAttribute element = (SimpleMetaAttribute) iterator.next();
        if (element.inheritable) {
          result.put(key, element);

代码示例来源:origin: net.jadler/jadler-core

/**
 * Removes all occurrences of the given header in this stub response (using a case insensitive search)
 * and sets its single value.
 * @param name header name
 * @param value header value
 */
@SuppressWarnings("unchecked")
void setHeaderCaseInsensitive(final String name, final String value) {
  final MultiMap result = new MultiValueMap();
  
  for (final Object o: this.headers.keySet()) {
    final String key = (String) o; //fucking non-generics MultiMap
    if (!name.equalsIgnoreCase(key)) {
       //copy all other headers to the result multimap
      for(final String s: (Collection<String>)this.headers.get(o)) {
        result.put(o, s);
      }
    }
  }
  
  this.headers.clear();
  this.headers.putAll(result);
  this.addHeader(name, value);
}

代码示例来源:origin: commons-collections/commons-collections

public void testPutAll_Map1() {
  MultiMap original = new MultiHashMap();
  original.put("key", "object1");
  original.put("key", "object2");
  MultiHashMap test = new MultiHashMap();
  test.put("keyA", "objectA");
  test.put("key", "object0");
  test.putAll(original);
  assertEquals(2, test.size());
  assertEquals(4, test.totalSize());
  assertEquals(1, test.getCollection("keyA").size());
  assertEquals(3, test.getCollection("key").size());
  assertEquals(true, test.containsValue("objectA"));
  assertEquals(true, test.containsValue("object0"));
  assertEquals(true, test.containsValue("object1"));
  assertEquals(true, test.containsValue("object2"));
}

代码示例来源:origin: hibernate/hibernate-tools

/**
 * Copies all the values from one MultiMap to another.
 * This method is needed because the (undocumented) behaviour of 
 * MultiHashMap.putAll in versions of Commons Collections prior to 3.0
 * was to replace the collection in the destination, whereas in 3.0
 * it adds the collection from the source as an _element_ of the collection
 * in the destination.  This method makes no assumptions about the implementation
 * of the MultiMap, and should work with all versions.
 * 
 * @param destination
 * @param specific
 */
public static void copyMultiMap(MultiMap destination, MultiMap specific) {
  for (Iterator<?> keyIterator = specific.keySet().iterator(); keyIterator.hasNext(); ) {
    Object key = keyIterator.next();
    Collection<?> c = (Collection<?>)specific.get(key);
    for (Iterator<?> valueIterator = c.iterator(); valueIterator.hasNext(); ) 
      destination.put(key, valueIterator.next() );
  }
}

代码示例来源:origin: org.jmockring/jmockring-core

/**
 * @param allServers
 * @throws IllegalArgumentException if any of the context configurations are inconsistent
 */
private void validateContextsConfiguration(Server[] allServers) {
  MultiMap bootstraps = new MultiValueMap();
  for (Server serverConfig : allServers) {
    // 1. Validate Class<->Name uniqueness
    if (bootstraps.containsKey(serverConfig.bootstrap())) {
      // server already defined in another context: check name
      Collection allNames = (Collection) bootstraps.get(serverConfig.bootstrap());
      if (allNames.contains(serverConfig.name())) {
        // same class & same name : not good
        throw new IllegalArgumentException(
            String.format("Duplicate server context definition for [%s] and name [%s]. Consider using @Server#name()",
                serverConfig.bootstrap().getName(),
                serverConfig.name())
        );
      }
    }
    bootstraps.put(serverConfig.bootstrap(), serverConfig.name());
    // 2. Check if context is configured
    if (serverConfig.dynamicContexts().length == 0 && serverConfig.webContexts().length == 0) {
      throw new IllegalArgumentException("No context configurations found for execution of class " + serverConfig.bootstrap().getName());
    }
  }
}

代码示例来源:origin: com.atlassian.jira/jira-api

/**
 * Will return a collection of issue type ids that are in use on issues that have values for the specified
 * custom field id.
 *
 * @param customFieldId the custom field id
 * @return collection of issue type ids that are in use on issues that have values for the specified
 * custom field id
 */
public Collection /*<String>*/getIssueTypeIdsForRequiredCustomField(final String customFieldId)
{
  return (Collection) issueTypesInUse.get(customFieldId);
}

代码示例来源:origin: com.atlassian.jira/jira-tests

public Map toMap()
  {
    Map paramMap = new HashMap();
    for (Object key : map.keySet())
    {
      List list = (List) map.get(key);
      String[] vals = new String[list.size()];
      for (int i = 0; i < vals.length; i++)
      {
        vals[i] = String.valueOf(list.get(i));

      }
      paramMap.put(key, vals);
    }
    return paramMap;
  }
}

代码示例来源:origin: com.manydesigns/portofino-pageactions

@Override
public MultiMap initEmbeddedPageActions() {
  if(embeddedPageActions == null) {
    MultiMap mm = new MultiValueMap();
    Layout layout = pageInstance.getLayout();
    for(ChildPage childPage : layout.getChildPages()) {
                page);
          mm.put(layoutContainerInParent, embeddedPageAction);
        } catch (PageNotActiveException e) {
          logger.warn("Embedded page action is not active, skipping! " + pageDir, e);
    for(Object entryObj : mm.entrySet()) {
      Map.Entry entry = (Map.Entry) entryObj;
      List pageActionContainer = (List) entry.getValue();

代码示例来源:origin: andyczy/czy-study-java-commons-utils

multiMap.put( "Sean" , "C/C++" );
multiMap.put( "Sean" , "OO" );
multiMap.put( "Sean" , "Java" );
multiMap.put( "Sean" , ".NET" );
multiMap.remove( "Sean" , "C/C++" );
System.out.println( "Sean's skill set: " + multiMap.get( "Sean" ));
System.out.println(StringUtils.repeat( "=" , 40));

代码示例来源:origin: info.magnolia/magnolia-module-cache

public InMemoryCachedEntry(byte[] out, String contentType, String characterEncoding, int statusCode, MultiMap headers, long modificationDate, String originalUrl, int timeToLiveInSeconds) throws IOException {
  super(contentType, characterEncoding, statusCode, headers, modificationDate, originalUrl, timeToLiveInSeconds);
  // content which is actually of a compressed type must stay that way
  if (GZipUtil.isGZipped(out)) {
    this.gzippedContent = out;
    boolean isGzippedResponse = headers.containsKey("Content-Encoding") && ((Collection)headers.get("Content-Encoding")).contains("gzip");
    if(isGzippedResponse){
      this.plainContent = GZipUtil.ungzip(out);
    }
    // in case of serving a gzip file (gif for instance)
    else{
      this.plainContent = null;
    }
  } else {
    this.gzippedContent = GZipUtil.gzip(out);
    this.plainContent = out;
  }
}

代码示例来源:origin: org.apache.cocoon/cocoon-expression-language-impl

private void removeAt(String path, Object value) {
  if (path == null) {
    throw new NullPointerException("Path cannot be null.");
  }
  if (path.length() == 0) {
    throw new IllegalArgumentException("Path cannot be empty");
  }
  Map map = locateMapAt(path, false);
  String key = path.substring(path.lastIndexOf(SEGMENT_SEPARATOR) + 1, path.length());
  if (map == null) {
    return;
  }
  multiValueMapForLocated.remove(key, value);
  if (multiValueMap.containsKey(key)) {
    map.put(key, ((StackReversedIteration) multiValueMap.get(key)).peek());
  } else {
    map.remove(key);
  }
}

代码示例来源:origin: info.magnolia/magnolia-module-cache

private void replaceHeader(String name, Object value) {
  if (responseExpirationCalculator == null || !responseExpirationCalculator.addHeader(name, value)) {
    headers.remove(name);
    headers.put(name, value);
  }
}

代码示例来源:origin: org.mule.modules/mule-module-http

@Override
public Collection<String> getHeaderNames()
{
  return headers.keySet();
}

代码示例来源:origin: org.jvnet.jaxbvalidation/jaxbvalidation-shared

public void unregisterValidationEventHandler(final ValidationEventLocator locator, final ValidationEventHandler handler)
{
 handlersMap.remove(locator, handler);
}

代码示例来源:origin: com.atlassian.jira/jira-api

public FieldConfig getOneAndOnlyConfig()
{
  final MultiMap configsByConfig = getConfigsByConfig();
  if ((configsByConfig != null) && (configsByConfig.size() == 1))
  {
    return (FieldConfig) configsByConfig.keySet().iterator().next();
  }
  else
  {
    if (configsByConfig != null)
    {
      log.warn("There is not exactly one config for this scheme (" + getId() + "). Configs are " + configsByConfig + ".");
    }
    return null;
  }
}

代码示例来源:origin: org.integratedmodelling/klab-common

public static void removeRolesFor(INamespace namespace) {
  List<Pair<IConcept, RoleDescriptor>> toRemove = new ArrayList<>();
  for (Object o : roles.values()) {
    RoleDescriptor rd = (RoleDescriptor) o;
    if (rd.namespaceId.equals(namespace.getId())) {
      toRemove.add(new Pair<>(rd.role, rd));
    }
  }
  for (Pair<IConcept, RoleDescriptor> r : toRemove) {
    roles.remove(r.getFirst(), r.getSecond());
  }
}

相关文章