Java Code Examples for com.google.common.collect.Maps#newLinkedHashMapWithExpectedSize()

The following examples show how to use com.google.common.collect.Maps#newLinkedHashMapWithExpectedSize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TensorFlowExtras.java    From zoltar with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch a list of operations from a {@link Session.Runner}, run it, extract output {@link
 * Tensor}s as {@link JTensor}s and close them.
 *
 * @param runner {@link Session.Runner} to fetch operations and extract outputs from.
 * @param fetchOps operations to fetch.
 * @return a {@link Map} of operations and output {@link JTensor}s. Map keys are in the same order
 *     as {@code fetchOps}.
 */
public static Map<String, JTensor> runAndExtract(
    final Session.Runner runner, final String... fetchOps) {
  for (final String op : fetchOps) {
    runner.fetch(op);
  }
  final Map<String, JTensor> result = Maps.newLinkedHashMapWithExpectedSize(fetchOps.length);
  final List<Tensor<?>> tensors = runner.run();
  try {
    for (int i = 0; i < fetchOps.length; i++) {
      final Tensor<?> tensor = tensors.get(i);
      result.put(fetchOps[i], JTensor.create(tensor));
    }
  } finally {
    tensors.forEach(Tensor::close);
  }
  return result;
}
 
Example 2
Source File: PublicXmlResourceValue.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Override
public int serializeTo(int sourceId, Namespaces namespaces, OutputStream output)
    throws IOException {
  Map<String, String> assignments = Maps.newLinkedHashMapWithExpectedSize(typeToId.size());
  for (Map.Entry<ResourceType, Optional<Integer>> entry : typeToId.entrySet()) {
    Optional<Integer> value = entry.getValue();
    String stringValue = value.isPresent() ? value.get().toString() : MISSING_ID_VALUE;
    assignments.put(entry.getKey().toString(), stringValue);
  }
  SerializeFormat.DataValue.Builder builder =
      XmlResourceValues.newSerializableDataValueBuilder(sourceId);
  builder.setXmlValue(
      builder
          .getXmlValueBuilder()
          .setType(SerializeFormat.DataValueXml.XmlType.PUBLIC)
          .putAllNamespace(namespaces.asMap())
          .putAllMappedStringValue(assignments));
  return XmlResourceValues.serializeProtoDataValue(output, builder);
}
 
Example 3
Source File: BuildType.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Creates a new Selector with a custom error message for when no conditions match. */
Selector(
    ImmutableMap<?, ?> x,
    Object what,
    @Nullable LabelConversionContext context,
    Type<T> originalType,
    String noMatchError)
    throws ConversionException {
  this.originalType = originalType;
  LinkedHashMap<Label, T> result = Maps.newLinkedHashMapWithExpectedSize(x.size());
  ImmutableSet.Builder<Label> defaultValuesBuilder = ImmutableSet.builder();
  boolean foundDefaultCondition = false;
  for (Map.Entry<?, ?> entry : x.entrySet()) {
    Label key = LABEL.convert(entry.getKey(), what, context);
    if (key.equals(DEFAULT_CONDITION_LABEL)) {
      foundDefaultCondition = true;
    }
    if (entry.getValue() == Starlark.NONE) {
      // { "//condition": None } is the same as not setting the value.
      result.put(key, originalType.getDefaultValue());
      defaultValuesBuilder.add(key);
    } else {
      String selectBranch = what == null
          ? null
          : String.format("each branch in select expression of %s (including '%s')",
              what.toString(), key.toString());
      result.put(key, originalType.convert(entry.getValue(), selectBranch, context));
    }
  }
  this.map = Collections.unmodifiableMap(result);
  this.noMatchError = noMatchError;
  this.conditionsWithDefaultValues = defaultValuesBuilder.build();
  this.hasDefaultCondition = foundDefaultCondition;
}
 
Example 4
Source File: OptionsBase.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a mapping from option names to values, for each option on this object, including
 * inherited ones. The mapping is a copy, so subsequent mutations to it or to this object are
 * independent. Entries are sorted alphabetically.
 */
public final Map<String, Object> asMap() {
  List<OptionDefinition> definitions = OptionsData.getAllOptionDefinitionsForClass(getClass());
  Map<String, Object> map = Maps.newLinkedHashMapWithExpectedSize(definitions.size());
  for (OptionDefinition definition : definitions) {
    map.put(definition.getOptionName(), getValueFromDefinition(definition));
  }
  return map;
}
 
Example 5
Source File: ModuleEffectiveStatementImpl.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private ModuleEffectiveStatementImpl(final @NonNull ModuleStmtContext ctx) {
    super(ctx, findPrefix(ctx.delegate(), "module", ctx.getStatementArgument()));
    submodules = ctx.getSubmodules();

    qnameModule = verifyNotNull(ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.delegate()));

    final String localPrefix = findFirstEffectiveSubstatementArgument(PrefixEffectiveStatement.class).get();
    final Builder<String, ModuleEffectiveStatement> prefixToModuleBuilder = ImmutableMap.builder();
    prefixToModuleBuilder.put(localPrefix, this);
    appendPrefixes(ctx, prefixToModuleBuilder);
    prefixToModule = prefixToModuleBuilder.build();

    final Map<QNameModule, String> tmp = Maps.newLinkedHashMapWithExpectedSize(prefixToModule.size() + 1);
    tmp.put(qnameModule, localPrefix);
    for (Entry<String, ModuleEffectiveStatement> e : prefixToModule.entrySet()) {
        tmp.putIfAbsent(e.getValue().localQNameModule(), e.getKey());
    }
    namespaceToPrefix = ImmutableMap.copyOf(tmp);

    final Map<String, StmtContext<?, ?, ?>> includedSubmodules =
            ctx.getAllFromCurrentStmtCtxNamespace(IncludedSubmoduleNameToModuleCtx.class);
    nameToSubmodule = includedSubmodules == null ? ImmutableMap.of()
            : ImmutableMap.copyOf(Maps.transformValues(includedSubmodules,
                submodule -> (SubmoduleEffectiveStatement) submodule.buildEffective()));

    final Map<QName, StmtContext<?, ExtensionStatement, ExtensionEffectiveStatement>> extensions =
            ctx.getAllFromCurrentStmtCtxNamespace(ExtensionNamespace.class);
    qnameToExtension = extensions == null ? ImmutableMap.of()
            : ImmutableMap.copyOf(Maps.transformValues(extensions, StmtContext::buildEffective));
    final Map<QName, StmtContext<?, FeatureStatement, FeatureEffectiveStatement>> features =
            ctx.getAllFromCurrentStmtCtxNamespace(FeatureNamespace.class);
    qnameToFeature = features == null ? ImmutableMap.of()
            : ImmutableMap.copyOf(Maps.transformValues(features, StmtContext::buildEffective));
    final Map<QName, StmtContext<?, IdentityStatement, IdentityEffectiveStatement>> identities =
            ctx.getAllFromCurrentStmtCtxNamespace(IdentityNamespace.class);
    qnameToIdentity = identities == null ? ImmutableMap.of()
            : ImmutableMap.copyOf(Maps.transformValues(identities, StmtContext::buildEffective));
}
 
Example 6
Source File: JavaCompileAction.java    From bazel with Apache License 2.0 5 votes vote down vote up
private ImmutableMap<String, String> getEffectiveEnvironment(
    ActionExecutionContext actionExecutionContext) {
  LinkedHashMap<String, String> effectiveEnvironment =
      Maps.newLinkedHashMapWithExpectedSize(env.size());
  env.resolve(effectiveEnvironment, actionExecutionContext.getClientEnv());
  return ImmutableMap.copyOf(effectiveEnvironment);
}
 
Example 7
Source File: CppLinkAction.java    From bazel with Apache License 2.0 5 votes vote down vote up
public ImmutableMap<String, String> getEnvironment(Map<String, String> clientEnv) {
  LinkedHashMap<String, String> result = Maps.newLinkedHashMapWithExpectedSize(env.size());
  env.resolve(result, clientEnv);

  result.putAll(toolchainEnv);

  if (!executionRequirements.containsKey(ExecutionRequirements.REQUIRES_DARWIN)) {
    // This prevents gcc from writing the unpredictable (and often irrelevant)
    // value of getcwd() into the debug info.
    result.put("PWD", "/proc/self/cwd");
  }
  return ImmutableMap.copyOf(result);
}
 
Example 8
Source File: SelectorFactory.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link Selector} by converting a given map.
 *
 * @param rawAttributes a map with attributes represented in a format produced by build file
 *     parsers (i.e. non-coerced.)
 */
public Selector<Object> createSelector(
    CellNameResolver cellNameResolver,
    ForwardRelativePath pathRelativeToProjectRoot,
    Map<String, ?> rawAttributes,
    String noMatchMessage) {
  LinkedHashMap<SelectorKey, Object> result =
      Maps.newLinkedHashMapWithExpectedSize(rawAttributes.size());
  Set<SelectorKey> nullConditions = new HashSet<>();
  for (Entry<String, ?> entry : rawAttributes.entrySet()) {
    String key = entry.getKey();
    SelectorKey selectorKey;
    if (key.equals(SelectorKey.DEFAULT_KEYWORD)) {
      selectorKey = SelectorKey.DEFAULT;
    } else {
      selectorKey =
          new SelectorKey(
              ConfigurationBuildTargets.convert(
                  unconfiguredBuildTargetViewFactory.createForPathRelativeToProjectRoot(
                      pathRelativeToProjectRoot, key, cellNameResolver)));
    }
    if (entry.getValue() == Runtime.NONE) {
      result.remove(selectorKey);
      nullConditions.add(selectorKey);
    } else {
      result.put(selectorKey, entry.getValue());
      nullConditions.remove(selectorKey);
    }
  }

  return new Selector<>(
      ImmutableMap.copyOf(result), ImmutableSet.copyOf(nullConditions), noMatchMessage);
}
 
Example 9
Source File: InstanceIdToCompositeNodes.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static NodeIdentifierWithPredicates reorderPredicates(final List<QName> keys,
        final NodeIdentifierWithPredicates arg) {
    if (Iterables.elementsEqual(keys, arg.keySet())) {
        // Iteration order matches key order, reuse the identifier
        return arg;
    }

    // We care about iteration order here!
    final LinkedHashMap<QName, Object> map = Maps.newLinkedHashMapWithExpectedSize(arg.size());
    for (QName qname : keys) {
        final Object value = arg.getValue(qname);
        if (value != null) {
            map.put(qname, value);
        }
    }
    if (map.size() < arg.size()) {
        // Okay, this should not happen, but let's handle that anyway
        LOG.debug("Extra predicates in {} while expecting {}", arg, keys);
        for (Entry<QName, Object> entry : arg.entrySet()) {
            map.putIfAbsent(entry.getKey(), entry.getValue());
        }
    }

    // This copy retains iteration order and since we have more than one argument, it should always be
    // and ImmutableOffsetMap -- which is guaranteed to be taken as-is
    final Map<QName, Object> copy = ImmutableOffsetMap.orderedCopyOf(map);
    verify(copy instanceof ImmutableOffsetMap);
    return NodeIdentifierWithPredicates.of(arg.getNodeType(), (ImmutableOffsetMap<QName, Object>) copy);
}
 
Example 10
Source File: L1CacheRepositoryDecorator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Looks up the Entities for a List of entity IDs. Those present in the cache are returned from
 * cache. The missing ones are retrieved from the decoratedRepository.
 *
 * @param entityIds list of entity IDs to look up
 * @param fetch containing attributes to retrieve, can be null
 * @return List of {@link Entity}s
 */
private Collection<Entity> findAllWithCache(
    List<Object> entityIds, @Nullable @CheckForNull Fetch fetch) {
  EntityType entityType = getEntityType();

  List<Object> missingEntityIds = null;
  Map<Object, Entity> entityMap = Maps.newLinkedHashMapWithExpectedSize(entityIds.size());

  for (Object entityId : entityIds) {
    Optional<CacheHit<Entity>> optionalCacheHit = l1Cache.get(entityType, entityId, fetch);
    if (optionalCacheHit.isPresent()) {
      entityMap.put(entityId, optionalCacheHit.get().getValue());
    } else {
      // placeholder value to reserve location in linked map
      entityMap.put(entityId, null);
      if (missingEntityIds == null) {
        missingEntityIds = new ArrayList<>(entityIds.size());
      }
      missingEntityIds.add(entityId);
    }
  }

  if (missingEntityIds != null && !missingEntityIds.isEmpty()) {
    // TODO retrieve with fetch and cache with fetch (also see findOneByIdWithCache)
    Stream<Entity> entityStream = delegate().findAll(missingEntityIds.stream());

    // replace placeholder values with actual values
    entityStream.forEach(
        entity -> {
          entityMap.put(entity.getIdValue(), entity);
          // TODO cache nulls for ids for which no entity exists
          l1Cache.put(entity);
        });
  }

  return entityMap.values();
}
 
Example 11
Source File: AbstractConfigurableNetwork.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Constructs a graph with the properties specified in {@code builder}.
 */
AbstractConfigurableNetwork(NetworkBuilder<? super N, ? super E> builder) {
  this(
      builder,
      Maps.<N, NodeConnections<N, E>>newLinkedHashMapWithExpectedSize(
          builder.expectedNodeCount.or(DEFAULT_MAP_SIZE)),
      Maps.<E, N>newLinkedHashMapWithExpectedSize(
          builder.expectedEdgeCount.or(DEFAULT_MAP_SIZE)));
}
 
Example 12
Source File: AbstractConfigurableNetwork.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Constructs a graph with the properties specified in {@code builder}.
 */

AbstractConfigurableNetwork(NetworkBuilder<? super N, ? super E> builder) {
  this(builder, Maps.<N, NodeConnections<N, E>>newLinkedHashMapWithExpectedSize(builder.expectedNodeCount.or(DEFAULT_MAP_SIZE)), Maps.<E, N>newLinkedHashMapWithExpectedSize(builder.expectedEdgeCount.or(DEFAULT_MAP_SIZE)));
}
 
Example 13
Source File: SubmoduleEffectiveStatementImpl.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
SubmoduleEffectiveStatementImpl(final StmtContext<String, SubmoduleStatement, SubmoduleEffectiveStatement> ctx) {
    super(ctx, findSubmodulePrefix(ctx));

    final String belongsToModuleName = firstAttributeOf(ctx.declaredSubstatements(), BelongsToStatement.class);
    final QNameModule belongsToModuleQName = ctx.getFromNamespace(ModuleNameToModuleQName.class,
            belongsToModuleName);

    final Builder<String, ModuleEffectiveStatement> prefixToModuleBuilder = ImmutableMap.builder();
    appendPrefixes(ctx, prefixToModuleBuilder);
    prefixToModule = prefixToModuleBuilder.build();

    final Map<QNameModule, String> tmp = Maps.newLinkedHashMapWithExpectedSize(prefixToModule.size());
    for (Entry<String, ModuleEffectiveStatement> e : prefixToModule.entrySet()) {
        tmp.putIfAbsent(e.getValue().localQNameModule(), e.getKey());
    }
    namespaceToPrefix = ImmutableMap.copyOf(tmp);

    final Optional<Revision> submoduleRevision = findFirstEffectiveSubstatementArgument(
        RevisionEffectiveStatement.class);
    this.qnameModule = QNameModule.create(belongsToModuleQName.getNamespace(), submoduleRevision).intern();

    /*
     * Because of possible circular chains of includes between submodules we can
     * collect only submodule contexts here and then build them during
     * sealing of this statement.
     */
    final Map<String, StmtContext<?, ?, ?>> includedSubmodulesMap = ctx.getAllFromCurrentStmtCtxNamespace(
        IncludedSubmoduleNameToModuleCtx.class);
    if (includedSubmodulesMap != null) {
        final Set<StmtContext<?, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>>>
            submoduleContextsInit = new HashSet<>();
        for (final StmtContext<?, ?, ?> submoduleCtx : includedSubmodulesMap.values()) {
            submoduleContextsInit.add(
                (StmtContext<?, SubmoduleStatement, EffectiveStatement<String, SubmoduleStatement>>)submoduleCtx);
        }
        submoduleContexts = ImmutableSet.copyOf(submoduleContextsInit);
    } else {
        submoduleContexts = ImmutableSet.of();
    }

    if (!submoduleContexts.isEmpty()) {
        ((Mutable<?, ?, ?>) ctx).addMutableStmtToSeal(this);
        sealed = false;
    } else {
        submodules = ImmutableSet.of();
        sealed = true;
    }
}
 
Example 14
Source File: AbstractConfigurableNetwork.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Constructs a graph with the properties specified in {@code builder}.
 */

AbstractConfigurableNetwork(NetworkBuilder<? super N, ? super E> builder) {
  this(builder, Maps.<N, NodeConnections<N, E>>newLinkedHashMapWithExpectedSize(builder.expectedNodeCount.or(DEFAULT_MAP_SIZE)), Maps.<E, N>newLinkedHashMapWithExpectedSize(builder.expectedEdgeCount.or(DEFAULT_MAP_SIZE)));
}
 
Example 15
Source File: AbstractConfigurableGraph.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Constructs a graph with the properties specified in {@code builder}.
 */

AbstractConfigurableGraph(GraphBuilder<? super N> builder) {
  this(builder, Maps.<N, NodeAdjacencies<N>>newLinkedHashMapWithExpectedSize(builder.expectedNodeCount.or(DEFAULT_MAP_SIZE)));
}
 
Example 16
Source File: AbstractConfigurableNetwork.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Constructs a graph with the properties specified in {@code builder}.
 */

AbstractConfigurableNetwork(NetworkBuilder<? super N, ? super E> builder) {
  this(builder, Maps.<N, NodeConnections<N, E>>newLinkedHashMapWithExpectedSize(builder.expectedNodeCount.or(DEFAULT_MAP_SIZE)), Maps.<E, N>newLinkedHashMapWithExpectedSize(builder.expectedEdgeCount.or(DEFAULT_MAP_SIZE)));
}
 
Example 17
Source File: AbstractConfigurableGraph.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Constructs a graph with the properties specified in {@code builder}.
 */

AbstractConfigurableGraph(GraphBuilder<? super N> builder) {
  this(builder, Maps.<N, NodeAdjacencies<N>>newLinkedHashMapWithExpectedSize(builder.expectedNodeCount.or(DEFAULT_MAP_SIZE)));
}
 
Example 18
Source File: LibraryInfoBuilder.java    From j2cl with Apache License 2.0 4 votes vote down vote up
public void addType(
    Type type,
    String headerFilePath,
    String implFilePath,
    Map<Member, com.google.j2cl.common.SourcePosition> outputSourceInfoByMember) {

  if (!isPrunableType(type.getTypeDescriptor())) {
    return;
  }

  TypeInfo.Builder typeInfoBuilder =
      TypeInfo.newBuilder()
          .setTypeId(getTypeId(type.getTypeDescriptor()))
          .setHeaderSourceFilePath(headerFilePath)
          .setImplSourceFilePath(implFilePath);

  DeclaredTypeDescriptor superTypeDescriptor = type.getSuperTypeDescriptor();
  if (superTypeDescriptor != null
      && !superTypeDescriptor.isNative()
      && !TypeDescriptors.isJavaLangObject(superTypeDescriptor)) {
    typeInfoBuilder.setExtendsType(getTypeId(superTypeDescriptor));
  }

  for (DeclaredTypeDescriptor superInterfaceType : type.getSuperInterfaceTypeDescriptors()) {
    if (!superInterfaceType.isNative() && !superInterfaceType.isJsFunctionInterface()) {
      typeInfoBuilder.addImplementsType(getTypeId(superInterfaceType));
    }
  }

  // Collect references to getter and setter for the same field under the name of the field,
  // creating only one MemberInfo instance that combines all the references appearing in their
  // bodies.
  Map<String, MemberInfo.Builder> memberInfoBuilderByName =
      Maps.newLinkedHashMapWithExpectedSize(type.getMembers().size());

  for (Member member : type.getMembers()) {
    MemberDescriptor memberDescriptor = member.getDescriptor();
    String memberName = getMemberId(memberDescriptor);
    boolean isJsAccessible = isJsAccessible(memberDescriptor);

    MemberInfo.Builder builder =
        memberInfoBuilderByName.computeIfAbsent(
            memberName,
            m ->
                MemberInfo.newBuilder()
                    .setName(memberName)
                    .setStatic(member.isStatic())
                    .setJsAccessible(isJsAccessible));

    com.google.j2cl.common.SourcePosition jsSourcePosition = outputSourceInfoByMember.get(member);
    if (jsSourcePosition != null) {
      builder.setPosition(createSourcePosition(jsSourcePosition));
    }

    collectReferencedTypesAndMethodInvocations(member, builder);
  }

  libraryInfo.addType(
      typeInfoBuilder.addAllMember(
          memberInfoBuilderByName.values().stream()
              .map(MemberInfo.Builder::build)
              .collect(Collectors.toList())));
}
 
Example 19
Source File: StarlarkCallable.java    From bazel with Apache License 2.0 3 votes vote down vote up
/**
 * Defines the "fast" implementation of function calling for a callable value.
 *
 * <p>Do not call this function directly. Use the {@link Starlark#call} or {@link
 * Starlark#fastcall} function to make a call, as it handles necessary book-keeping such as
 * maintenance of the call stack, exception handling, and so on.
 *
 * <p>The fastcall implementation takes ownership of the two arrays, and may retain them
 * indefinitely or modify them. The caller must not modify or even access the two arrays after
 * making the call.
 *
 * <p>This method defines the low-level or "fast" calling convention. A more convenient interface
 * is provided by the {@link #call} method, which provides a signature analogous to {@code def
 * f(*args, **kwargs)}, or possibly the "self-call" feature of the {@link StarlarkMethod#selfCall}
 * annotation mechanism.
 *
 * <p>The default implementation forwards the call to {@code call}, after rejecting any duplicate
 * named arguments. Other implementations of this method should similarly reject duplicates.
 *
 * @param thread the StarlarkThread in which the function is called
 * @param positional a list of positional arguments
 * @param named a list of named arguments, as alternating Strings/Objects. May contain dups.
 */
default Object fastcall(StarlarkThread thread, Object[] positional, Object[] named)
    throws EvalException, InterruptedException {
  LinkedHashMap<String, Object> kwargs = Maps.newLinkedHashMapWithExpectedSize(named.length >> 1);
  for (int i = 0; i < named.length; i += 2) {
    if (kwargs.put((String) named[i], named[i + 1]) != null) {
      throw Starlark.errorf("%s got multiple values for parameter '%s'", this, named[i]);
    }
  }
  return call(thread, Tuple.of(positional), Dict.wrap(thread.mutability(), kwargs));
}
 
Example 20
Source File: CollectionUtils.java    From fastjgame with Apache License 2.0 2 votes vote down vote up
/**
 * 创建足够容量的Map,可减少扩容次数,适合用在能估算最大容量的时候;
 *
 * @param expectedSize 期望添加的元素数量
 * @param <K>          key的类型
 * @param <V>          value的类型
 * @return Map
 */
public static <K, V> LinkedHashMap<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) {
    return Maps.newLinkedHashMapWithExpectedSize(expectedSize);
}