Java Code Examples for com.google.common.collect.ImmutableBiMap#Builder

The following examples show how to use com.google.common.collect.ImmutableBiMap#Builder . 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: FactoryDescriptor.java    From auto with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a bi-map of duplicate {@link ImplementationMethodDescriptor}s by their respective
 * {@link FactoryMethodDescriptor}.
 */
private static ImmutableBiMap<FactoryMethodDescriptor, ImplementationMethodDescriptor>
    createDuplicateMethodDescriptorsBiMap(
        ImmutableSet<FactoryMethodDescriptor> factoryMethodDescriptors,
        ImmutableSet<ImplementationMethodDescriptor> implementationMethodDescriptors) {

  ImmutableBiMap.Builder<FactoryMethodDescriptor, ImplementationMethodDescriptor> builder =
      ImmutableBiMap.builder();

  for (FactoryMethodDescriptor factoryMethodDescriptor : factoryMethodDescriptors) {
    for (ImplementationMethodDescriptor implementationMethodDescriptor :
        implementationMethodDescriptors) {

      boolean areDuplicateMethodDescriptors =
          areDuplicateMethodDescriptors(factoryMethodDescriptor, implementationMethodDescriptor);
      if (areDuplicateMethodDescriptors) {
        builder.put(factoryMethodDescriptor, implementationMethodDescriptor);
        break;
      }
    }
  }

  return builder.build();
}
 
Example 2
Source File: ResourcesFilter.java    From buck with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
ImmutableBiMap<Path, Path> createInResDirToOutResDirMap(
    ImmutableList<Path> resourceDirectories, ImmutableList.Builder<Path> filteredResDirectories) {
  ImmutableBiMap.Builder<Path, Path> filteredResourcesDirMapBuilder = ImmutableBiMap.builder();

  List<Path> outputDirs = getRawResDirectories();
  Preconditions.checkState(
      outputDirs.size() == resourceDirectories.size(),
      "Directory list sizes don't match.  This is a bug.");
  Iterator<Path> outIter = outputDirs.iterator();
  for (Path resDir : resourceDirectories) {
    Path filteredResourceDir = outIter.next();
    filteredResourcesDirMapBuilder.put(resDir, filteredResourceDir);
    filteredResDirectories.add(filteredResourceDir);
  }
  return filteredResourcesDirMapBuilder.build();
}
 
Example 3
Source File: HierarchicalTypeStore.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
HierarchicalTypeStore(MemRepository repository, HierarchicalType hierarchicalType) throws RepositoryException {
    this.hierarchicalType = (IConstructableType) hierarchicalType;
    this.repository = repository;
    ImmutableMap.Builder<AttributeInfo, IAttributeStore> b =
            new ImmutableBiMap.Builder<>();
    typeNameList = Lists.newArrayList((String) null);
    ImmutableList<AttributeInfo> l = hierarchicalType.immediateAttrs;
    for (AttributeInfo i : l) {
        b.put(i, AttributeStores.createStore(i));
    }
    attrStores = b.build();

    ImmutableList.Builder<HierarchicalTypeStore> b1 = new ImmutableList.Builder<>();
    Set<String> allSuperTypeNames = hierarchicalType.getAllSuperTypeNames();
    for (String s : allSuperTypeNames) {
        b1.add(repository.getStore(s));
    }
    superTypeStores = b1.build();

    nextPos = 0;
    idPosMap = new HashMap<>();
    freePositions = new ArrayList<>();

    lock = new ReentrantReadWriteLock();
}
 
Example 4
Source File: RuleSetModelEvaluator.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
private ImmutableBiMap.Builder<String, SimpleRule> collectRule(Rule rule, AtomicInteger index, ImmutableBiMap.Builder<String, SimpleRule> builder){

			if(rule instanceof SimpleRule){
				SimpleRule simpleRule = (SimpleRule)rule;

				builder = EntityUtil.put(simpleRule, index, builder);
			} else

			if(rule instanceof CompoundRule){
				CompoundRule compoundRule = (CompoundRule)rule;

				builder = collectRules(compoundRule.getRules(), index, builder);
			} else

			{
				throw new UnsupportedElementException(rule);
			}

			return builder;
		}
 
Example 5
Source File: NeuralNetworkEvaluator.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public BiMap<String, NeuralEntity> load(NeuralNetwork neuralNetwork){
	ImmutableBiMap.Builder<String, NeuralEntity> builder = new ImmutableBiMap.Builder<>();

	AtomicInteger index = new AtomicInteger(1);

	NeuralInputs neuralInputs = neuralNetwork.getNeuralInputs();
	for(NeuralInput neuralInput : neuralInputs){
		builder = EntityUtil.put(neuralInput, index, builder);
	}

	List<NeuralLayer> neuralLayers = neuralNetwork.getNeuralLayers();
	for(NeuralLayer neuralLayer : neuralLayers){
		List<Neuron> neurons = neuralLayer.getNeurons();

		for(int i = 0; i < neurons.size(); i++){
			Neuron neuron = neurons.get(i);

			builder = EntityUtil.put(neuron, index, builder);
		}
	}

	return builder.build();
}
 
Example 6
Source File: CaseInsensitiveImmutableBiMap.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link ImmutableBiMap} with key case-insensitivity.
 * @param map map to copy from
 * @param <VALUE> type of values to be stored in the map
 * @return key case-insensitive immutable bi-map
 */
public static <VALUE> CaseInsensitiveImmutableBiMap<VALUE> newImmutableMap(final Map<? extends String, ? extends VALUE> map) {
  final ImmutableBiMap.Builder<String, VALUE> builder = ImmutableBiMap.builder();
  for (final Entry<? extends String, ? extends VALUE> entry : map.entrySet()) {
    builder.put(entry.getKey().toLowerCase(), entry.getValue());
  }
  return new CaseInsensitiveImmutableBiMap<>(builder.build());
}
 
Example 7
Source File: RuleSetModelEvaluator.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
private ImmutableBiMap.Builder<String, SimpleRule> collectRules(List<Rule> rules, AtomicInteger index, ImmutableBiMap.Builder<String, SimpleRule> builder){

			for(Rule rule : rules){
				builder = collectRule(rule, index, builder);
			}

			return builder;
		}
 
Example 8
Source File: ElementCostOfDataStructures.java    From memory-measurer with Apache License 2.0 5 votes vote down vote up
public ImmutableBiMap construct(int entries) {
  ImmutableBiMap.Builder builder = ImmutableBiMap.builder();
  for (int i = 0; i < entries; i++) {
    builder.put(newEntry(), newEntry());
  }
  return builder.build();
}
 
Example 9
Source File: DebugPathSanitizer.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public <E extends Exception> ImmutableBiMap<Path, String> deserialize(
    ValueCreator<E> deserializer) throws E {
  int size = deserializer.createInteger();
  ImmutableBiMap.Builder<Path, String> builder = ImmutableBiMap.builderWithExpectedSize(size);
  Path[] keys = new Path[size];
  for (int i = 0; i < size; i++) {
    keys[i] = Paths.get(deserializer.createString());
  }
  for (Path k : keys) {
    builder.put(k, deserializer.createString());
  }
  return builder.build();
}
 
Example 10
Source File: ClassType.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
public ITypedReferenceableInstance createInstanceWithTraits(Id id, AtlasSystemAttributes systemAttributes, Referenceable r, String... traitNames)
throws AtlasException {

    ImmutableMap.Builder<String, ITypedStruct> b = new ImmutableBiMap.Builder<>();
    if (traitNames != null) {
        for (String t : traitNames) {
            TraitType tType = typeSystem.getDataType(TraitType.class, t);
            IStruct iTraitObject = r == null ? null : r.getTrait(t);
            ITypedStruct trait = iTraitObject == null ? tType.createInstance() :
                    tType.convert(iTraitObject, Multiplicity.REQUIRED);
            b.put(t, trait);
        }
    }

    return new ReferenceableInstance(id == null ? new Id(getName()) : id, getName(), systemAttributes, fieldMapping,
            new boolean[fieldMapping.fields.size()], new boolean[fieldMapping.fields.size()],
            fieldMapping.numBools == 0 ? null : new boolean[fieldMapping.numBools],
            fieldMapping.numBytes == 0 ? null : new byte[fieldMapping.numBytes],
            fieldMapping.numShorts == 0 ? null : new short[fieldMapping.numShorts],
            fieldMapping.numInts == 0 ? null : new int[fieldMapping.numInts],
            fieldMapping.numLongs == 0 ? null : new long[fieldMapping.numLongs],
            fieldMapping.numFloats == 0 ? null : new float[fieldMapping.numFloats],
            fieldMapping.numDoubles == 0 ? null : new double[fieldMapping.numDoubles],
            fieldMapping.numBigDecimals == 0 ? null : new BigDecimal[fieldMapping.numBigDecimals],
            fieldMapping.numBigInts == 0 ? null : new BigInteger[fieldMapping.numBigInts],
            fieldMapping.numDates == 0 ? null : new Date[fieldMapping.numDates],
            fieldMapping.numStrings == 0 ? null : new String[fieldMapping.numStrings],
            fieldMapping.numArrays == 0 ? null : new ImmutableList[fieldMapping.numArrays],
            fieldMapping.numMaps == 0 ? null : new ImmutableMap[fieldMapping.numMaps],
            fieldMapping.numStructs == 0 ? null : new StructInstance[fieldMapping.numStructs],
            fieldMapping.numReferenceables == 0 ? null : new ReferenceableInstance[fieldMapping.numReferenceables],
            fieldMapping.numReferenceables == 0 ? null : new Id[fieldMapping.numReferenceables], b.build());
}
 
Example 11
Source File: StructStore.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
StructStore(AttributeInfo aInfo) throws RepositoryException {
    super(aInfo);
    this.structType = (StructType) aInfo.dataType();
    ImmutableMap.Builder<AttributeInfo, IAttributeStore> b = new ImmutableBiMap.Builder<>();
    Collection<AttributeInfo> l = structType.fieldMapping.fields.values();
    for (AttributeInfo i : l) {
        b.put(i, AttributeStores.createStore(i));
    }
    attrStores = b.build();

}
 
Example 12
Source File: ElementCostOfDataStructures.java    From memory-measurer with Apache License 2.0 5 votes vote down vote up
public ImmutableBiMap construct(int entries) {
  ImmutableBiMap.Builder builder = ImmutableBiMap.builder();
  for (int i = 0; i < entries; i++) {
    builder.put(newEntry(), newEntry());
  }
  return builder.build();
}
 
Example 13
Source File: _ResponseLinking.java    From tac-kbp-eal with MIT License 5 votes vote down vote up
public ResponseLinking copyWithFilteredResponses(final Predicate<Response> toKeepCondition) {
  final Set<Response> newIncompletes = Sets.filter(incompleteResponses(), toKeepCondition);
  final ImmutableSet.Builder<ResponseSet> newResponseSetsB = ImmutableSet.builder();
  final ImmutableBiMap.Builder<String, ResponseSet> responseSetsIdB = ImmutableBiMap.builder();
  // to account for ResponseSets merging due to lost annotation
  final Set<ResponseSet> alreadyAdded = Sets.newHashSet();
  for (final ResponseSet responseSet : responseSets()) {
    final ImmutableSet<Response> okResponses = FluentIterable.from(responseSet.asSet())
        .filter(toKeepCondition).toSet();
    if (!okResponses.isEmpty()) {
      final ResponseSet newResponseSet = ResponseSet.from(okResponses);
      if(alreadyAdded.contains(newResponseSet)) {
        continue;
      }
      alreadyAdded.add(newResponseSet);
      newResponseSetsB.add(newResponseSet);
      if (responseSetIds().isPresent()) {
        responseSetsIdB.put(responseSetIds().get().inverse().get(responseSet), newResponseSet);
      }
    }
  }

  final ImmutableSet<ResponseSet> newResponseSets = newResponseSetsB.build();
  final ResponseLinking.Builder ret = ResponseLinking.builder().docID(docID())
      .responseSets(newResponseSets).incompleteResponses(newIncompletes);
  if (responseSetIds().isPresent()) {
    ret.responseSetIds(responseSetsIdB.build());
  }
  return ret.build();
}
 
Example 14
Source File: TreeModelEvaluator.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public BiMap<String, Node> load(TreeModel treeModel){
	ImmutableBiMap.Builder<String, Node> builder = new ImmutableBiMap.Builder<>();

	builder = collectNodes(treeModel.getNode(), new AtomicInteger(1), builder);

	return builder.build();
}
 
Example 15
Source File: TieredSFCIndexFactory.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * @param baseDefinitions an array of Numeric Dimension Definitions
 * @param maxBitsPerDimension the max cardinality for the Index Strategy
 * @param sfcType the type of space filling curve (e.g. Hilbert)
 * @param maxEstimatedDuplicatedIds the max number of duplicate SFC IDs
 * @return an Index Strategy object with a tier for every incremental cardinality between the
 *         lowest max bits of precision and 0
 */
public static TieredSFCIndexStrategy createFullIncrementalTieredStrategy(
    final NumericDimensionDefinition[] baseDefinitions,
    final int[] maxBitsPerDimension,
    final SFCType sfcType,
    final Long maxEstimatedDuplicatedIds) {
  if (maxBitsPerDimension.length == 0) {
    final ImmutableBiMap<Integer, Byte> emptyMap = ImmutableBiMap.of();
    return new TieredSFCIndexStrategy(baseDefinitions, new SpaceFillingCurve[] {}, emptyMap);
  }
  int numIndices = Integer.MAX_VALUE;
  for (final int element : maxBitsPerDimension) {
    numIndices = Math.min(numIndices, element + 1);
  }
  final SpaceFillingCurve[] spaceFillingCurves = new SpaceFillingCurve[numIndices];
  final ImmutableBiMap.Builder<Integer, Byte> sfcIndexToTier = ImmutableBiMap.builder();
  for (int sfcIndex = 0; sfcIndex < numIndices; sfcIndex++) {
    final SFCDimensionDefinition[] sfcDimensions =
        new SFCDimensionDefinition[baseDefinitions.length];
    int maxBitsOfPrecision = Integer.MIN_VALUE;
    for (int d = 0; d < baseDefinitions.length; d++) {
      final int bitsOfPrecision = maxBitsPerDimension[d] - (numIndices - sfcIndex - 1);
      maxBitsOfPrecision = Math.max(bitsOfPrecision, maxBitsOfPrecision);
      sfcDimensions[d] = new SFCDimensionDefinition(baseDefinitions[d], bitsOfPrecision);
    }
    sfcIndexToTier.put(sfcIndex, (byte) maxBitsOfPrecision);

    spaceFillingCurves[sfcIndex] = SFCFactory.createSpaceFillingCurve(sfcDimensions, sfcType);
  }
  if ((maxEstimatedDuplicatedIds != null) && (maxEstimatedDuplicatedIds > 0)) {
    return new TieredSFCIndexStrategy(
        baseDefinitions,
        spaceFillingCurves,
        sfcIndexToTier.build(),
        maxEstimatedDuplicatedIds);
  }
  return new TieredSFCIndexStrategy(baseDefinitions, spaceFillingCurves, sfcIndexToTier.build());
}
 
Example 16
Source File: TieredSFCIndexFactory.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * @param baseDefinitions an array of Numeric Dimension Definitions
 * @param maxBitsPerDimension the max cardinality for the Index Strategy
 * @param sfcType the type of space filling curve (e.g. Hilbert)
 * @param numIndices the number of tiers of the Index Strategy
 * @return an Index Strategy object with a specified number of tiers
 */
public static TieredSFCIndexStrategy createEqualIntervalPrecisionTieredStrategy(
    final NumericDimensionDefinition[] baseDefinitions,
    final int[] maxBitsPerDimension,
    final SFCType sfcType,
    final int numIndices) {
  // Subtracting one from the number tiers prevents an extra tier. If
  // we decide to create a catch-all, then we can ignore the subtraction.
  final SpaceFillingCurve[] spaceFillingCurves = new SpaceFillingCurve[numIndices];
  final ImmutableBiMap.Builder<Integer, Byte> sfcIndexToTier = ImmutableBiMap.builder();
  for (int sfcIndex = 0; sfcIndex < numIndices; sfcIndex++) {
    final SFCDimensionDefinition[] sfcDimensions =
        new SFCDimensionDefinition[baseDefinitions.length];
    int maxBitsOfPrecision = Integer.MIN_VALUE;
    for (int d = 0; d < baseDefinitions.length; d++) {
      int bitsOfPrecision;
      if (numIndices == 1) {
        bitsOfPrecision = maxBitsPerDimension[d];
      } else {
        final double bitPrecisionIncrement = ((double) maxBitsPerDimension[d] / (numIndices - 1));
        bitsOfPrecision = (int) (bitPrecisionIncrement * sfcIndex);
      }
      maxBitsOfPrecision = Math.max(bitsOfPrecision, maxBitsOfPrecision);
      sfcDimensions[d] = new SFCDimensionDefinition(baseDefinitions[d], bitsOfPrecision);
    }
    sfcIndexToTier.put(sfcIndex, (byte) maxBitsOfPrecision);
    spaceFillingCurves[sfcIndex] = SFCFactory.createSpaceFillingCurve(sfcDimensions, sfcType);
  }

  return new TieredSFCIndexStrategy(baseDefinitions, spaceFillingCurves, sfcIndexToTier.build());
}
 
Example 17
Source File: RpcEnum.java    From mobly-bundled-snippets with Apache License 2.0 4 votes vote down vote up
private RpcEnum(ImmutableBiMap.Builder<String, Integer> builder, int minSdk) {
    mEnums = builder.build();
}
 
Example 18
Source File: ImmutableCollectors.java    From helper with MIT License 4 votes vote down vote up
public static <K, V> Collector<Map.Entry<? extends K, ? extends V>, ImmutableBiMap.Builder<K, V>, ImmutableBiMap<K, V>> toBiMap() {
    //noinspection unchecked
    return (Collector) BIMAP;
}
 
Example 19
Source File: ResponseMapping.java    From tac-kbp-eal with MIT License 4 votes vote down vote up
public ResponseLinking apply(ResponseLinking responseLinking) {
  final Function<Response, Response> responseMapping = MapUtils.asFunction(replacedResponses,
      Functions.<Response>identity());
  final Predicate<Response> notDeleted = not(in(deletedResponses));

  final ImmutableSet.Builder<ResponseSet> newResponseSetsB = ImmutableSet.builder();
  final ImmutableMap.Builder<ResponseSet, ResponseSet> oldResponseSetToNewB = ImmutableMap.builder();
  for (final ResponseSet responseSet : responseLinking.responseSets()) {
    final ImmutableSet<Response> filteredResponses = FluentIterable.from(responseSet)
        .filter(notDeleted)
        .transform(responseMapping).toSet();
    if (!filteredResponses.isEmpty()) {
      final ResponseSet derived = ResponseSet.from(filteredResponses);
      newResponseSetsB.add(derived);
      oldResponseSetToNewB.put(responseSet, derived);
    }
  }

  final ImmutableSet<ResponseSet> newResponseSets = newResponseSetsB.build();
  final Predicate<Response> notLinked = not(in(ImmutableSet.copyOf(
      Iterables.concat(newResponseSets))));
  final ImmutableSet<Response> newIncompletes =
      FluentIterable.from(responseLinking.incompleteResponses())
          .filter(notDeleted)
          .transform(responseMapping)
          .filter(notLinked)
          .toSet();

  final Optional<ImmutableBiMap<String, ResponseSet>> newResponseSetIDMap;
  if (responseLinking.responseSetIds().isPresent()) {
    final BiMap<String, ResponseSet> responseSetIDs = responseLinking.responseSetIds().get();
    final ImmutableMap<ResponseSet, ResponseSet> oldResponseSetToNew = oldResponseSetToNewB.build();
    final Multimap<ResponseSet, ResponseSet> newResponseToOld = oldResponseSetToNew.asMultimap().inverse();
    final ImmutableBiMap.Builder<String, ResponseSet> newResponseSetIDMapB =
        ImmutableBiMap.builder();
    // since response sets may lose responses and no longer be unique, we choose the earliest alphabetical ID
    for(final ResponseSet nu: newResponseToOld.keySet()) {
      final ImmutableSet.Builder<String> candidateIDsB = ImmutableSet.builder();
      for(final ResponseSet old: newResponseToOld.get(nu)) {
        candidateIDsB.add(responseSetIDs.inverse().get(old));
      }
      final ImmutableSet<String> candidateIDs = candidateIDsB.build();
      final String newID = Ordering.natural().sortedCopy(candidateIDs).get(0);
      if(candidateIDs.size() > 1) {
        // only log if we're converting multiple sets.
        log.debug("Collapsing response sets {} to {}", candidateIDs, newID);
      }
      newResponseSetIDMapB.put(newID, nu);
    }
    newResponseSetIDMap = Optional.of(newResponseSetIDMapB.build());
  } else {
    newResponseSetIDMap = Optional.absent();
  }

  return ResponseLinking.builder().docID(responseLinking.docID())
      .responseSets(newResponseSets).incompleteResponses(newIncompletes)
      .responseSetIds(newResponseSetIDMap).build();
}
 
Example 20
Source File: BDDFiniteDomain.java    From batfish with Apache License 2.0 4 votes vote down vote up
private static <V> BiMap<V, BDD> computeValueBdds(BDDInteger var, Set<V> values) {
  ImmutableBiMap.Builder<V, BDD> builder = ImmutableBiMap.builder();
  forEachWithIndex(values, (idx, src) -> builder.put(src, var.value(idx)));
  return builder.build();
}