Tabnine Logo
Map.computeIfAbsent
Code IndexAdd Tabnine to your IDE (free)

How to use
computeIfAbsent
method
in
java.util.Map

Best Java code snippets using java.util.Map.computeIfAbsent (Showing top 20 results out of 19,116)

Refine searchRefine arrow

  • List.add
  • Map.put
  • Map.get
  • Map.Entry.getKey
  • Map.Entry.getValue
  • Set.add
  • Map.entrySet
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;
}
java.utilMapcomputeIfAbsent

Popular methods of Map

  • put
    Maps the specified key to the specified value.
  • get
  • entrySet
    Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes t
  • containsKey
    Returns whether this Map contains the specified key.
  • keySet
    Returns a set of the keys contained in this Map. The Set is backed by this Map so changes to one are
  • values
    Returns a Collection view of the values contained in this map. The collection is backed by the map,
  • remove
  • size
    Returns the number of mappings in this Map.
  • isEmpty
    Returns true if this map contains no key-value mappings.
  • clear
    Removes all elements from this Map, leaving it empty.
  • putAll
    Copies all of the mappings from the specified map to this map (optional operation). The effect of th
  • forEach
  • putAll,
  • forEach,
  • equals,
  • hashCode,
  • getOrDefault,
  • containsValue,
  • putIfAbsent,
  • compute,
  • merge

Popular in Java

  • Making http post requests using okhttp
  • getContentResolver (Context)
  • getResourceAsStream (ClassLoader)
  • findViewById (Activity)
  • Thread (java.lang)
    A thread is a thread of execution in a program. The Java Virtual Machine allows an application to ha
  • ServerSocket (java.net)
    This class represents a server-side socket that waits for incoming client connections. A ServerSocke
  • Locale (java.util)
    Locale represents a language/country/variant combination. Locales are used to alter the presentatio
  • Set (java.util)
    A Set is a data structure which does not allow duplicate elements.
  • Stack (java.util)
    Stack is a Last-In/First-Out(LIFO) data structure which represents a stack of objects. It enables u
  • LogFactory (org.apache.commons.logging)
    Factory for creating Log instances, with discovery and configuration features similar to that employ
  • CodeWhisperer alternatives
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now