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

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

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

Map.computeIfAbsent介绍

暂无

代码示例

canonical example by Tabnine

private void mappingWordsLength(List<String> wordsList) {
 Map<Integer, Set<String>> mapping = new HashMap<>();
 for (String word : wordsList) {
  mapping.computeIfAbsent(word.length(), HashSet::new).add(word);
 }
 List<Integer> lengths = new LinkedList<>(mapping.keySet());
 Collections.sort(lengths);
 lengths.forEach(n -> System.out.println(mapping.get(n).size() + " words with " + n + " chars"));
}

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

public void addListener(String key, ConfigurationListener configurationListener) {
  Set<ConfigurationListener> listeners = this.keyListeners.computeIfAbsent(key, k -> new CopyOnWriteArraySet<>());
  listeners.add(configurationListener);
}

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

@Override
public void add(K key, @Nullable V value) {
  List<V> values = this.targetMap.computeIfAbsent(key, k -> new LinkedList<>());
  values.add(value);
}

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

@Override
public ColumnValueSelector<?> makeColumnValueSelector(String columnName)
{
 final ColumnValueSelector existing = columnSelectorMap.get(columnName);
 if (existing != null) {
  return existing;
 }
 return columnSelectorMap.computeIfAbsent(columnName, delegate::makeColumnValueSelector);
}

代码示例来源:origin: MovingBlocks/Terasology

private void loadBlocks() {
  blockFamilyIds = Maps.newHashMap();
  gameInfo.getManifest().getBlockIdMap().entrySet().forEach(blockId -> {
    String familyName = blockId.getKey().split(":")[0].toLowerCase();
    blockFamilyIds.computeIfAbsent(familyName, k -> new ArrayList<>());
    blockFamilyIds.get(familyName).add(blockId.toString());
  });
  blocks.setList(Lists.newArrayList(blockFamilyIds.keySet()));
}

代码示例来源:origin: mpusher/mpush

@Override
public long hincrBy(String key, String field, long value) {
  Map fields = ((Map) cache.computeIfAbsent(key, k -> new ConcurrentHashMap<>()));
  Number num = (Number) fields.get(field);
  long result = num.longValue() + 1;
  fields.put(field, result);
  executor.execute(this::writeToFile);
  return result;
}

代码示例来源:origin: prestodb/presto

public Collection<Set<T>> getEquivalentClasses()
  {
    // map from root element to all element in the tree
    Map<T, Set<T>> rootToTreeElements = new LinkedHashMap<>();
    for (Map.Entry<T, Entry<T>> entry : map.entrySet()) {
      T node = entry.getKey();
      T root = findInternal(node);
      rootToTreeElements.computeIfAbsent(root, unused -> new LinkedHashSet<>());
      rootToTreeElements.get(root).add(node);
    }
    return rootToTreeElements.values();
  }
}

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

public List<JavaPackage> getPackages() {
  List<JavaClass> classList = getClasses();
  if (classList.isEmpty()) {
    return Collections.emptyList();
  }
  Map<String, List<JavaClass>> map = new HashMap<>();
  for (JavaClass javaClass : classList) {
    String pkg = javaClass.getPackage();
    List<JavaClass> clsList = map.computeIfAbsent(pkg, k -> new ArrayList<>());
    clsList.add(javaClass);
  }
  List<JavaPackage> packages = new ArrayList<>(map.size());
  for (Map.Entry<String, List<JavaClass>> entry : map.entrySet()) {
    packages.add(new JavaPackage(entry.getKey(), entry.getValue()));
  }
  Collections.sort(packages);
  for (JavaPackage pkg : packages) {
    pkg.getClasses().sort(Comparator.comparing(JavaClass::getName));
  }
  return Collections.unmodifiableList(packages);
}

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

/**
 * Bind the given prefix to the given namespace.
 * @param prefix the namespace prefix
 * @param namespaceUri the namespace uri
 */
public void bindNamespaceUri(String prefix, String namespaceUri) {
  Assert.notNull(prefix, "No prefix given");
  Assert.notNull(namespaceUri, "No namespaceUri given");
  if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) {
    this.defaultNamespaceUri = namespaceUri;
  }
  else {
    this.prefixToNamespaceUri.put(prefix, namespaceUri);
    Set<String> prefixes =
        this.namespaceUriToPrefixes.computeIfAbsent(namespaceUri, k -> new LinkedHashSet<>());
    prefixes.add(prefix);
  }
}

代码示例来源: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: prestodb/presto

/**
 * Sets a catalog property for the session.  The property name and value must
 * only contain characters from US-ASCII and must not be for '='.
 */
public SessionBuilder setCatalogSessionProperty(String catalogName, String propertyName, String propertyValue)
{
  checkArgument(transactionId == null, "Catalog session properties cannot be set if there is an open transaction");
  catalogSessionProperties.computeIfAbsent(catalogName, id -> new HashMap<>()).put(propertyName, propertyValue);
  return this;
}

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

public void init() {
  if (!isValid()) {
    return;
  }
  tags.forEach(tag -> {
    tagnameToAddresses.put(tag.getName(), tag.getAddresses());
    tag.getAddresses().forEach(addr -> {
      List<String> tagNames = addressToTagnames.computeIfAbsent(addr, k -> new ArrayList<>());
      tagNames.add(tag.getName());
    });
  });
}

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

public void registerSource( String classifier, DiagnosticsReportSource source )
{
  availableClassifiers.add( classifier );
  additionalSources.computeIfAbsent( classifier, c -> new ArrayList<>() ).add( source );
}

代码示例来源:origin: prestodb/presto

private static Map<String, Map<ColumnStatisticType, Block>> createColumnToComputedStatisticsMap(Map<ColumnStatisticMetadata, Block> computedStatistics)
{
  Map<String, Map<ColumnStatisticType, Block>> result = new HashMap<>();
  computedStatistics.forEach((metadata, block) -> {
    Map<ColumnStatisticType, Block> columnStatistics = result.computeIfAbsent(metadata.getColumnName(), key -> new HashMap<>());
    columnStatistics.put(metadata.getStatisticType(), block);
  });
  return result.entrySet()
      .stream()
      .collect(toImmutableMap(Entry::getKey, entry -> ImmutableMap.copyOf(entry.getValue())));
}

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

public void tryToSchedule(Map<ExecutorDetails, String> execToComp, RAS_Node node, WorkerSlot workerSlot) {
  ExecutorDetails exec = currentExec();
  String comp = execToComp.get(exec);
  LOG.trace("Trying assignment of {} {} to {}", exec, comp, workerSlot);
  //It is possible that this component is already scheduled on this node or worker.  If so when we backtrack we cannot remove it
  okToRemoveFromWorker[execIndex] = workerCompAssignment.computeIfAbsent(workerSlot, (k) -> new HashSet<>()).add(comp);
  okToRemoveFromNode[execIndex] = nodeCompAssignment.computeIfAbsent(node, (k) -> new HashSet<>()).add(comp);
  node.assignSingleExecutor(workerSlot, exec, td);
}

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

private Map<String, AtomicInteger> getScheduledCount(TopologyDetails topologyDetails) {
  String topoId = topologyDetails.getId();
  SchedulerAssignment assignment = cluster.getAssignmentById(topoId);
  Map<String, AtomicInteger> scheduledCount = new HashMap<>();
  if (assignment != null) {
    for (Map.Entry<WorkerSlot, Collection<ExecutorDetails>> entry :
      assignment.getSlotToExecutors().entrySet()) {
      String superId = entry.getKey().getNodeId();
      String rackId = superIdToRack.get(superId);
      scheduledCount.computeIfAbsent(rackId, (rid) -> new AtomicInteger(0))
        .getAndAdd(entry.getValue().size());
    }
  }
  return scheduledCount;
}

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

for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) {
  JedisPool jedisPool = entry.getValue();
  try {
    try (Jedis jedis = jedisPool.getResource()) {
          for (String key : keys) {
            String serviceKey = toServicePath(key);
            Set<String> sk = serviceKeys.computeIfAbsent(serviceKey, k -> new HashSet<>());
            sk.add(key);
    exception = new RpcException("Failed to subscribe service from redis registry. registry: " + entry.getKey() + ", service: " + url + ", cause: " + t.getMessage(), t);

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

@Override
public T addResources(Map<String, Double> resources) {
  if (resources != null && !resources.isEmpty()) {
    String currConf = commons.get(id).get_json_conf();
    Map<String, Object> conf = parseJson(currConf);
    Map<String, Double> currentResources =
      (Map<String, Double>) conf.computeIfAbsent(Config.TOPOLOGY_COMPONENT_RESOURCES_MAP, (k) -> new HashMap<>());
    currentResources.putAll(resources);
    commons.get(id).set_json_conf(JSONValue.toJSONString(conf));
  }
  return (T) this;
}

代码示例来源:origin: hs-web/hsweb-framework

@Override
public Map<ObjectMetadata.ObjectType, List<? extends ObjectMetadata>> getMetas() {
  return parserRepo
      .computeIfAbsent(DataSourceHolder.currentDatabaseType(), t -> new HashMap<>())
      .entrySet()
      .stream()
      .collect(Collectors.toMap(Map.Entry::getKey, entry -> {
        try {
          return entry.getValue().parseAll();
        } catch (SQLException e) {
          log.error("parse meta {} error", entry.getKey(), e);
          return new ArrayList<>();
        }
      }));
}

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

public GroupHolder<C, T> merge(GroupHolder<C, T> holder) {
  holder.elements.entrySet().forEach(e
    -> elements.computeIfAbsent(e.getKey(), createList)
    .addAll(e.getValue())
  );
  return this;
}

相关文章