java.util.Map.values()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(12.4k)|赞(0)|评价(0)|浏览(201)

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

Map.values介绍

[英]Returns a Collection of the values contained in this Map. The Collectionis backed by this Map so changes to one are reflected by the other. The Collection supports Collection#remove, Collection#removeAll, Collection#retainAll, and Collection#clear operations, and it does not support Collection#add or Collection#addAll operations.

This method returns a Collection which is the subclass of AbstractCollection. The AbstractCollection#iterator method of this subclass returns a "wrapper object" over the iterator of this Map's #entrySet(). The AbstractCollection#size method wraps this Map's #size method and the AbstractCollection#contains method wraps this Map's #containsValue method.

The collection is created when this method is called at first time and returned in response to all subsequent calls. This method may return different Collection when multiple calls to this method, since it has no synchronization performed.
[中]返回此映射中包含的值的集合。收藏品以这张地图为后盾,因此对其中一个的变化会被另一个反映出来。集合支持Collection#remove、Collection#removeAll、Collection#Retainal和Collection#clear操作,不支持Collection#add或Collection#addAll操作。
此方法返回一个集合,该集合是AbstractCollection的子类。该子类的AbstractCollection#iterator方法在该映射的#entrySet()的迭代器上返回一个“包装器对象”。AbstractCollection#size方法包装此映射的#size方法,AbstractCollection#contains方法包装此映射的#containsValue方法。
该集合是在第一次调用此方法时创建的,并在响应所有后续调用时返回。当多次调用此方法时,此方法可能返回不同的集合,因为它没有执行同步。

代码示例

代码示例来源:origin: google/guava

private static <V extends Enum<V>> Class<V> inferValueType(Map<?, V> map) {
 if (map instanceof EnumBiMap) {
  return ((EnumBiMap<?, V>) map).valueType;
 }
 checkArgument(!map.isEmpty());
 return map.values().iterator().next().getDeclaringClass();
}

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

public Map<String, Object> defaultValues() {
  Map<String, Object> defaultValues = new HashMap<>();
  for (ConfigKey key : configKeys.values()) {
    if (key.defaultValue != NO_DEFAULT_VALUE)
      defaultValues.put(key.name, key.defaultValue);
  }
  return defaultValues;
}

代码示例来源:origin: square/okhttp

public void ensureResourcesClosed() {
 List<String> openResources = new ArrayList<>();
 for (File file : openSources.values()) {
  openResources.add("Source for " + file);
 }
 for (File file : openSinks.values()) {
  openResources.add("Sink for " + file);
 }
 if (!openResources.isEmpty()) {
  StringBuilder builder = new StringBuilder("Resources acquired but not closed:");
  for (String resource : openResources) {
   builder.append("\n * ").append(resource);
  }
  throw new IllegalStateException(builder.toString());
 }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Filter out undesired attributes from the given model.
 * The return value can be either another {@link Map} or a single value object.
 * <p>The default implementation removes {@link BindingResult} instances and entries
 * not included in the {@link #setModelKeys modelKeys} property.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @return the value to be rendered
 */
@Override
protected Object filterModel(Map<String, Object> model) {
  Map<String, Object> result = new HashMap<>(model.size());
  Set<String> modelKeys = (!CollectionUtils.isEmpty(this.modelKeys) ? this.modelKeys : model.keySet());
  model.forEach((clazz, value) -> {
    if (!(value instanceof BindingResult) && modelKeys.contains(clazz) &&
        !clazz.equals(JsonView.class.getName()) &&
        !clazz.equals(FilterProvider.class.getName())) {
      result.put(clazz, value);
    }
  });
  return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result);
}

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

private void refreshLocalityGroup() {
  Map<Integer, NodeInfo> cachedTaskToNodePort = taskToNodePort.get();
  Map<String, String> hostToRack = getHostToRackMapping(cachedTaskToNodePort);
  localityGroup.values().stream().forEach(v -> v.clear());
  for (int target : targetTasks) {
    Scope scope = calculateScope(cachedTaskToNodePort, hostToRack, target);
    if (!localityGroup.containsKey(scope)) {
      localityGroup.put(scope, new ArrayList<>());
    }
    localityGroup.get(scope).add(target);
  }
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * In case of duplicate entries, we keep only the last updated element
 */
private void keepLastUpdatedUnique() {
  Map<String, SingleTokenStats> temp = new HashMap<>();
  this.tokenStats.forEach(candidate -> {
    SingleTokenStats current = temp.get(candidate.tokenUuid);
    if (current == null) {
      temp.put(candidate.tokenUuid, candidate);
    } else {
      int comparison = SingleTokenStats.COMP_BY_LAST_USE_THEN_COUNTER.compare(current, candidate);
      if (comparison < 0) {
        // candidate was updated more recently (or has a bigger counter in case of perfectly equivalent dates)
        temp.put(candidate.tokenUuid, candidate);
      }
    }
  });
  
  this.tokenStats = new ArrayList<>(temp.values());
}

代码示例来源:origin: alibaba/druid

public List<Map<String, Object>> getSqlStatDataList(Object datasource) {
  List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
  Map<?, ?> sqlStatMap = DruidDataSourceUtils.getSqlStatMap(datasource);
  for (Object sqlStat : sqlStatMap.values()) {
    Map<String, Object> data = JdbcSqlStatUtils.getData(sqlStat);
    long executeCount = (Long) data.get("ExecuteCount");
    long runningCount = (Long) data.get("RunningCount");
    if (executeCount == 0 && runningCount == 0) {
      continue;
    }
    result.add(data);
  }
  return result;
}

代码示例来源:origin: apache/incubator-dubbo

private List<Invoker<T>> toMergeInvokerList(List<Invoker<T>> invokers) {
  List<Invoker<T>> mergedInvokers = new ArrayList<>();
  Map<String, List<Invoker<T>>> groupMap = new HashMap<String, List<Invoker<T>>>();
  for (Invoker<T> invoker : invokers) {
    String group = invoker.getUrl().getParameter(Constants.GROUP_KEY, "");
    groupMap.computeIfAbsent(group, k -> new ArrayList<>());
    groupMap.get(group).add(invoker);
  }
  if (groupMap.size() == 1) {
    mergedInvokers.addAll(groupMap.values().iterator().next());
  } else if (groupMap.size() > 1) {
    for (List<Invoker<T>> groupList : groupMap.values()) {
      StaticDirectory<T> staticDirectory = new StaticDirectory<>(groupList);
      staticDirectory.buildRouterChain();
      mergedInvokers.add(cluster.join(staticDirectory));
    }
  } else {
    mergedInvokers = invokers;
  }
  return mergedInvokers;
}

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

@Override
public void configure(ParameterTool parameterTool) throws ProgramParametrizationException {
  super.configure(parameterTool);
  // add dimensions as ordered by dimension ID (dim0, dim1, dim2, ...)
  Map<Integer, String> dimensionMap = new TreeMap<>();
  // first parse all dimensions into a sorted map
  for (String key : parameterTool.toMap().keySet()) {
    if (key.startsWith(PREFIX)) {
      int dimensionId = Integer.parseInt(key.substring(PREFIX.length()));
      dimensionMap.put(dimensionId, parameterTool.get(key));
    }
  }
  // then store dimensions in order
  for (String field : dimensionMap.values()) {
    dimensions.add(new Dimension(field));
  }
}

代码示例来源:origin: SonarSource/sonarqube

public static List<Section> order(Collection<Section> sections, String... orderedNames) {
  Map<String, Section> alphabeticalOrderedMap = new TreeMap<>();
  sections.forEach(section -> alphabeticalOrderedMap.put(section.getName(), section));

  List<Section> result = new ArrayList<>(sections.size());
  stream(orderedNames).forEach(name -> {
   Section section = alphabeticalOrderedMap.remove(name);
   if (section != null) {
    result.add(section);
   }
  });
  result.addAll(alphabeticalOrderedMap.values());
  return result;
 }
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public List<URL> lookup(URL url) {
  List<URL> urls = new ArrayList<>();
  Map<String, List<URL>> notifiedUrls = getNotified().get(url);
  if (notifiedUrls != null && notifiedUrls.size() > 0) {
    for (List<URL> values : notifiedUrls.values()) {
      urls.addAll(values);
    for (URL u : getRegistered()) {
      if (UrlUtils.isMatch(url, u)) {
        urls.add(u);
    for (URL u : getSubscribed().keySet()) {
      if (UrlUtils.isMatch(url, u)) {
        urls.add(u);

代码示例来源:origin: google/guava

private static ImmutableList<Method> getAnnotatedMethodsNotCached(Class<?> clazz) {
 Set<? extends Class<?>> supertypes = TypeToken.of(clazz).getTypes().rawTypes();
 Map<MethodIdentifier, Method> identifiers = Maps.newHashMap();
 for (Class<?> supertype : supertypes) {
  for (Method method : supertype.getDeclaredMethods()) {
   if (method.isAnnotationPresent(Subscribe.class) && !method.isSynthetic()) {
    // TODO(cgdecker): Should check for a generic parameter type and error out
    Class<?>[] parameterTypes = method.getParameterTypes();
    checkArgument(
      parameterTypes.length == 1,
      "Method %s has @Subscribe annotation but has %s parameters."
        + "Subscriber methods must have exactly 1 parameter.",
      method,
      parameterTypes.length);
    MethodIdentifier ident = new MethodIdentifier(method);
    if (!identifiers.containsKey(ident)) {
     identifiers.put(ident, method);
    }
   }
  }
 }
 return ImmutableList.copyOf(identifiers.values());
}

代码示例来源:origin: Activiti/Activiti

public Map<String, VariableInstance> getVariableInstancesLocal() {
 Map<String, VariableInstance> variables = new HashMap<String, VariableInstance>();
 ensureVariableInstancesInitialized();
 for (VariableInstanceEntity variableInstance : variableInstances.values()) {
  variables.put(variableInstance.getName(), variableInstance);
 }
 for (String variableName : usedVariablesCache.keySet()) {
  variables.put(variableName, usedVariablesCache.get(variableName));
 }
 if (transientVariabes != null) {
  variables.putAll(transientVariabes);
 }
 return variables;
}

代码示例来源:origin: skylot/jadx

@Override
public List<IContainer> getSubBlocks() {
  List<IContainer> all = new ArrayList<>(2 + catchRegions.size());
  all.add(tryRegion);
  all.addAll(catchRegions.values());
  if (finallyRegion != null) {
    all.add(finallyRegion);
  }
  return Collections.unmodifiableList(all);
}

代码示例来源:origin: spring-projects/spring-framework

@Override
@Nullable
public SimpUser getUser(String userName) {
  // Prefer remote registries due to cross-server SessionLookup
  for (UserRegistrySnapshot registry : this.remoteRegistries.values()) {
    SimpUser user = registry.getUserMap().get(userName);
    if (user != null) {
      return user;
    }
  }
  return this.localRegistry.getUser(userName);
}

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

public List<TopicPartition> allPartitionsSorted(Map<String, Integer> partitionsPerTopic,
                        Map<String, Subscription> subscriptions) {
  SortedSet<String> topics = new TreeSet<>();
  for (Subscription subscription : subscriptions.values())
    topics.addAll(subscription.topics());
  List<TopicPartition> allPartitions = new ArrayList<>();
  for (String topic : topics) {
    Integer numPartitionsForTopic = partitionsPerTopic.get(topic);
    if (numPartitionsForTopic != null)
      allPartitions.addAll(AbstractPartitionAssignor.partitions(topic, numPartitionsForTopic));
  }
  return allPartitions;
}

代码示例来源:origin: redisson/redisson

public RFuture<Boolean> containsAllAsync(Collection<?> c) {
  List<Object> coll = new ArrayList<Object>(c);
  for (Iterator<Object> iterator = coll.iterator(); iterator.hasNext();) {
    Object value = iterator.next();
    for (Object val : state.values()) {
      if (val != NULL && isEqual(val, value)) {
        iterator.remove();
        break;
      }
    }
  }
  
  return set.containsAllAsync(coll);
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
  String key = exchange.getRequest().getQueryParams().getFirst(getParameterName());
  if (!StringUtils.hasText(key)) {
    return MEDIA_TYPE_ALL_LIST;
  }
  key = formatKey(key);
  MediaType match = this.mediaTypes.get(key);
  if (match == null) {
    match = MediaTypeFactory.getMediaType("filename." + key)
        .orElseThrow(() -> {
          List<MediaType> supported = new ArrayList<>(this.mediaTypes.values());
          return new NotAcceptableStatusException(supported);
        });
  }
  this.mediaTypes.putIfAbsent(key, match);
  return Collections.singletonList(match);
}

代码示例来源:origin: redisson/redisson

private Map getAllMultiInterfaces(MultiType type) {
  Map map = new HashMap();
  Iterator iter = type.interfaces.values().iterator();
  while (iter.hasNext()) {
    CtClass intf = (CtClass)iter.next();
    map.put(intf.getName(), intf);
    getAllInterfaces(intf, map);
  }
  return map;
}

代码示例来源:origin: jenkinsci/jenkins

public List<Plugin> getUpdates() {
  Map<String,Plugin> pluginMap = new LinkedHashMap<String, Plugin>();
  for (UpdateSite site : sites) {
    for (Plugin plugin: site.getUpdates()) {
      final Plugin existing = pluginMap.get(plugin.name);
      if (existing == null) {
        pluginMap.put(plugin.name, plugin);
      } else if (!existing.version.equals(plugin.version)) {
        // allow secondary update centers to publish different versions
        // TODO refactor to consolidate multiple versions of the same plugin within the one row
        final String altKey = plugin.name + ":" + plugin.version;
        if (!pluginMap.containsKey(altKey)) {
          pluginMap.put(altKey, plugin);
        }
      }
    }
  }
  return new ArrayList<Plugin>(pluginMap.values());
}

相关文章