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

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

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

HashMap.computeIfAbsent介绍

暂无

代码示例

代码示例来源:origin: GlowstoneMC/Glowstone

/**
 * Get the internal set of objectives corresponding to a given criteria.
 *
 * @param criteria The criteria to look up.
 * @return The set of objectives.
 */
Set<GlowObjective> getForCriteria(String criteria) {
  Set<GlowObjective> result = criteriaMap.computeIfAbsent(criteria, k -> new HashSet<>());
  return result;
}

代码示例来源:origin: GlowstoneMC/Glowstone

/**
 * Get the internal set of scores corresponding to a given entry.
 *
 * @param entry The entry to look up.
 * @return The set of scores.
 */
Set<GlowScore> getScoresForName(String entry) {
  Set<GlowScore> result = scoreMap.computeIfAbsent(entry, k -> new HashSet<>());
  return result;
}

代码示例来源:origin: oblac/jodd

/**
 * Adds profile property.
 */
public void putProfileProperty(final String key, final String value, final String profile, final boolean append) {
  Map<String, PropsEntry> map = profileProperties.computeIfAbsent(profile, k -> new HashMap<>());
  put(profile, map, key, value, append);
}

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

public Entry get(final String key) {
  HashMap<String, Entry> entryCache = this.entryCache;
  if (entryCache == null) {
    entryCache = this.entryCache = new HashMap<>();
  }
  return entryCache.computeIfAbsent(key, s -> new SimpleAttributesEntry(this, s));
}

代码示例来源:origin: JanusGraph/janusgraph

/**
 * Increases the count of object o by inc and returns the new count value
 *
 * @param o
 * @param inc
 * @return
 */
public double incBy(K o, double inc) {
  final Counter c = countMap.computeIfAbsent(o, k -> new Counter());
  c.count += inc;
  return c.count;
}

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

@Override
  public Logger getLogger(String name) {
    return consoleLoggers.computeIfAbsent(name, n -> new ConsoleLogger(n, verbose));
  }
}

代码示例来源:origin: gchq/Gaffer

@Override
  public <K, V> ICache<K, V> getCache(final String cacheName) {
    HashMapCache<K, V> cache = caches.computeIfAbsent(cacheName, k -> new HashMapCache<>(useJavaSerialisation));

    return cache;
  }
}

代码示例来源:origin: oracle/helidon

@Override
public Map<String, List<String>> headers() {
  HashMap<String, List<String>> map = new HashMap<>();
  for (Map.Entry<String, String> entry : nettyRequest.headers().entries()) {
    map.computeIfAbsent(entry.getKey(), s -> new ArrayList<>()).add(entry.getValue());
  }
  return map;
}

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

public ServerConnectionCollection getProxyIdCollection(ClientProxyMembershipID proxyID) {
 return proxyIdConnections.computeIfAbsent(proxyID, key -> new ServerConnectionCollection());
}

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

public SecurityFilter( Iterable<SecurityRule> securityRules )
{
  // For backwards compatibility
  for ( SecurityRule r : securityRules )
  {
    String rulePath = r.forUriPath();
    if ( !rulePath.endsWith( "*" ) )
    {
      rulePath = rulePath + "*";
    }
    UriPathWildcardMatcher uriPathWildcardMatcher = new UriPathWildcardMatcher( rulePath );
    HashSet<ForbiddingSecurityRule> ruleHashSet = rules.computeIfAbsent( uriPathWildcardMatcher, k -> new HashSet<>() );
    ruleHashSet.add( fromSecurityRule( r ) );
  }
}

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

List<Relationship> targetPreds = predecessors.computeIfAbsent( targetNode, k -> new LinkedList<>() );
targetPreds.add( relationship );

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

private int writeString(final DataOutput output, String string, final IdentityIntMap<Object> seen, final HashMap<String, String> stringCache, final int cnt) throws IOException {
  if (string == null) {
    output.write(ST_NULL);
    return cnt;
  }
  // make sure we never duplicate a string
  string = stringCache.computeIfAbsent(string, Function.identity());
  final int idx = seen.get(string, - 1);
  final int distance = cnt - idx;
  if (idx == -1 || distance > (1 << 14) - 1) {
    seen.put(string, cnt);
    output.write(ST_NEW_STRING);
    output.writeUTF(string);
    return cnt + 1;
  } else {
    if (distance < 127) {
      output.writeByte(ST_BACKREF_NEAR | distance);
    } else {
      assert distance <= 0x3fff;
      output.writeByte(ST_BACKREF_FAR | distance >> 8);
      output.writeByte(distance);
    }
    return cnt;
  }
}

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

EnvelopeSettings envelopeSettings = env.computeIfAbsent( crs, EnvelopeSettings::new );
int index = "xyz".indexOf( fields[1].toLowerCase() );
if ( index < 0 )

代码示例来源:origin: confluentinc/ksql

topicConsumerCount.forEach(
  (k, v) -> {
   results.computeIfAbsent(k, v1 -> new ArrayList<>()).add(v.intValue());
   results.get(k).add(topicConsumerGroupCount.get(k).size());

代码示例来源:origin: GlowstoneMC/Glowstone

/**
 * Returns a score, creating it if necessary.
 *
 * @param entry the key (e.g. player name or team name)
 * @return the score for {@code entry}
 * @throws IllegalArgumentException if {@code entry} is null
 * @throws IllegalStateException if this objective isn't registered with a scoreboard
 */
@Override
public Score getScore(String entry) throws IllegalArgumentException, IllegalStateException {
  checkNotNull(entry, "Entry cannot be null");
  checkValid();
  return scores.computeIfAbsent(entry, entryCopy -> {
    GlowScore score = new GlowScore(this, entryCopy);
    scores.put(entryCopy, score);
    scoreboard.getScoresForName(entryCopy).add(score);
    return score;
  });
}

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

public synchronized BuildState get(Lifespan lifespan)
{
  if (grouped) {
    return buildStatesMap.computeIfAbsent(lifespan, ignored -> new BuildState());
  }
  else {
    return buildStatesMap.computeIfAbsent(Lifespan.taskWide(), ignored -> new BuildState());
  }
}

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

static <T> EJBProxyInterceptorInformation<T> construct(Class<T> clazz, EJBClientContext clientContext) {
  final EJBProxyInformation<T> proxyInformation = EJBProxyInformation.forViewType(clazz);
  final Collection<EJBProxyInformation.ProxyMethodInfo> methods = proxyInformation.getMethods();
  final String className = clazz.getName();
  final InterceptorList list0 = EJBClientContext.defaultInterceptors;
  final InterceptorList list1 = clientContext.getGlobalInterceptors();
  final InterceptorList list2 = clientContext.getClassPathInterceptors();
  final InterceptorList list3 = clientContext.getConfiguredPerClassInterceptors().getOrDefault(className, EMPTY);
  final InterceptorList list5 = proxyInformation.getClassInterceptors();
  final IdentityHashMap<Method, InterceptorList> interceptorsByMethod = new IdentityHashMap<>(methods.size());
  final HashMap<InterceptorList, InterceptorList> cache = new HashMap<>();
  cache.computeIfAbsent(list0, Function.identity());
  final InterceptorList tailList = list3.combine(list2).combine(list1).combine(list0);
  cache.computeIfAbsent(tailList, Function.identity());
  for (EJBProxyInformation.ProxyMethodInfo method : methods) {
    // compile interceptor information
    final InterceptorList list4 = clientContext.getConfiguredPerMethodInterceptors().getOrDefault(className, emptyMap()).getOrDefault(method.getMethodLocator(), EMPTY);
    final InterceptorList list6 = method.getInterceptors();
    interceptorsByMethod.put(method.getMethod(), cache.computeIfAbsent(list6.combine(list5).combine(list4).combine(tailList), Function.identity()));
  }
  return new EJBProxyInterceptorInformation<T>(proxyInformation, interceptorsByMethod, cache.computeIfAbsent(list5.combine(tailList), Function.identity()));
}

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

sharingGroup = slotSharingGroups.computeIfAbsent(
    slotSharingGroupKey, (k) -> new SlotSharingGroup());
vertex.setSlotSharingGroup(sharingGroup);
Tuple2<SlotSharingGroup, CoLocationGroup> constraint = coLocationGroups.computeIfAbsent(
    coLocationGroupKey, (k) -> new Tuple2<>(sharingGroup, new CoLocationGroup()));

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

@Test
public void testReduceResultSet() {
  Map<Integer, SomethingWithLocations> result = dbRule.getSharedHandle()
    .createQuery("SELECT something.id, name, location FROM something NATURAL JOIN something_location")
    .reduceResultSet(new HashMap<Integer, SomethingWithLocations>(), (map, rs, ctx) -> {
      final String name = rs.getString("name");
      map.computeIfAbsent(rs.getInt("id"),
          id -> new SomethingWithLocations(new Something(id, name)))
        .at(rs.getString("location"));
      return map;
    });
  assertThat(result).hasSize(2)
    .containsEntry(1, new SomethingWithLocations(new Something(1, "tree")).at("outside"))
    .containsEntry(2, new SomethingWithLocations(new Something(2, "apple")).at("tree").at("pie"));
}

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

@Test
public void testReduceRowsWithSeed() {
  Map<Integer, SomethingWithLocations> result = dbRule.getSharedHandle()
    .createQuery("SELECT something.id, name, location FROM something NATURAL JOIN something_location")
    .reduceRows(new HashMap<Integer, SomethingWithLocations>(), (map, rr) -> {
      map.computeIfAbsent(rr.getColumn("id", Integer.class),
          id -> new SomethingWithLocations(rr.getRow(Something.class)))
        .locations
        .add(rr.getColumn("location", String.class));
      return map;
    });
  assertThat(result).hasSize(2)
    .containsEntry(1, new SomethingWithLocations(new Something(1, "tree")).at("outside"))
    .containsEntry(2, new SomethingWithLocations(new Something(2, "apple")).at("tree").at("pie"));
}

相关文章