com.google.common.collect.HashBiMap的实例源码

项目:n4js    文件:N4HeadlessCompiler.java   
private void configureResourceSetContainerState(final List<N4JSProject> allProjects) {
    // a container is a project.
    List<String> containers = new LinkedList<>();
    BiMap<String,N4JSProject> container2project = HashBiMap.create();

    // the URIs of all resources directly contained in a project/container.
    Multimap<String,URI> container2Uris = HashMultimap.create();

    for (N4JSProject project : allProjects) {
        String container = FileBasedWorkspace.N4FBPRJ + project.getLocation();
        container2project.put(container,project);
        containers.add(container);

        for (IN4JSSourceContainer sourceContainer : project.getSourceContainers()) {
            Iterables.addAll(container2Uris.get(container),sourceContainer);
        }
    }

    // Define the Mapping of Resources (URIs to Container === Projects),rsbAcs.configure(containers,container2Uris);
}
项目:neto    文件:NetoResourceUtil.java   
public Map<Integer,Class<? extends NetoJsonMessage>> opcodeMap(String filePath,String messagePackage) throws Exception {

        BiMap<Integer,Class<? extends NetoJsonMessage>> classBiMap = HashBiMap.create();

        File opcodeJsonFile = getFile(filePath);

        ObjectMapper ob = new ObjectMapper();

        JsonNode jsonNode = ob.readTree(opcodeJsonFile);
        Iterator<String> it = jsonNode.fieldNames();

        while(it.hasNext()) {
            StringBuilder sb = new StringBuilder();
            String className = it.next();
            int opcode = jsonNode.get(className).asInt();
            sb.append(messagePackage).append('.').append(className);
            Class<? extends NetoJsonMessage> aClass = (Class<? extends NetoJsonMessage>) Class.forName(sb.toString());
            classBiMap.put(opcode,aClass);
        }

        return classBiMap;
    }
项目:rejoiner    文件:GqlInputConverter.java   
GqlInputConverter build() {
  HashBiMap<String,Descriptor> mapping = HashBiMap.create();
  HashBiMap<String,EnumDescriptor> enumMapping = HashBiMap.create(getEnumMap(enumDescriptors));
  LinkedList<Descriptor> loop = new LinkedList<>(descriptors);

  Set<FileDescriptor> fileDescriptorSet = ProtoRegistry.extractDependencies(fileDescriptors);

  for (FileDescriptor fileDescriptor : fileDescriptorSet) {
    loop.addAll(fileDescriptor.getMessageTypes());
    enumMapping.putAll(getEnumMap(fileDescriptor.getEnumTypes()));
  }

  while (!loop.isEmpty()) {
    Descriptor descriptor = loop.pop();
    if (!mapping.containsKey(descriptor.getFullName())) {
      mapping.put(getReferenceName(descriptor),descriptor);
      loop.addAll(descriptor.getNestedTypes());
      enumMapping.putAll(getEnumMap(descriptor.getEnumTypes()));
    }
  }

  return new GqlInputConverter(
      ImmutableBiMap.copyOf(mapping),ImmutableBiMap.copyOf(enumMapping));
}
项目:rejoiner    文件:ProtoRegistry.java   
/** Applies the supplied modifications to the GraphQLTypes. */
private static BiMap<String,GraphQLType> modifyTypes(
    BiMap<String,GraphQLType> mapping,ImmutableListMultimap<String,TypeModification> modifications) {
  BiMap<String,GraphQLType> result = HashBiMap.create(mapping.size());
  for (String key : mapping.keySet()) {
    if (mapping.get(key) instanceof GraphQLObjectType) {
      GraphQLObjectType val = (GraphQLObjectType) mapping.get(key);
      if (modifications.containsKey(key)) {
        for (TypeModification modification : modifications.get(key)) {
          val = modification.apply(val);
        }
      }
      result.put(key,val);
    } else {
      result.put(key,mapping.get(key));
    }
  }
  return result;
}
项目:TextHIN    文件:FileUtils.java   
public static BiMap<String,String> loadStringToStringBiMap(String file,int from,int to) throws IOException {

    BiMap<String,String> res = HashBiMap.create();
    BufferedReader reader = IOUtils.getBufferedFileReader(file);
    String line;
    while ((line = reader.readLine()) != null) {
      String[] tokens = line.split("\t");
      if (res.containsKey(tokens[from]))
        throw new RuntimeException("Map already contains key: " + tokens[from]);
      if (res.inverse().containsKey(tokens[to]))
        throw new RuntimeException("Map already contains value: " + tokens[to]);
      res.put(tokens[from],tokens[to]);
    }
    reader.close();
    return res;
  }
项目:Equella    文件:XMLDataConverterTest.java   
public void testTypeMap()
{
    BiMap<String,Integer> map = HashBiMap.create();
    map.put("test1",1);
    map.put("test2",2);
    map.put("test3",3);
    map.put("test4",4);

    mappings.addNodeMapping(

    new ListMapping("collection","types/type",ArrayList.class,new NodeTypeMapping("","",map,new Integer(4))));
    getBean();

    assertEquals(1,bean.collection.get(0));
    assertEquals(2,bean.collection.get(1));
    assertEquals(3,bean.collection.get(2));
    assertEquals(4,bean.collection.get(3));

    getPropBagEx();

    assertEquals("test1",xml.getNode("types/type[0]"));
    assertEquals("test2",xml.getNode("types/type[1]"));
    assertEquals("test3",xml.getNode("types/type[2]"));
    assertEquals("test4",xml.getNode("types/type[3]"));
}
项目:optashift-employee-rostering    文件:TenantConfigurationEditor.java   
@PostConstruct
protected void initWidget() {
    for (DayOfWeek day : DayOfWeek.values()) {
        weekStart.addItem(day.toString());
    }

    // TODO: Make this more maintainable
    templateDurationIndexMap = HashBiMap.create();
    templateDuration.addItem("1 Week");
    templateDurationIndexMap.put(1,0);
    templateDuration.addItem("2 Weeks");
    templateDurationIndexMap.put(2,1);
    templateDuration.addItem("4 Weeks");
    templateDurationIndexMap.put(4,2);

    desiredWeightInput.setValidators(new DecimalMinValidator<Integer>(0));
    undesiredWeightInput.setValidators(new DecimalMinValidator<Integer>(0));
}
项目:SubgraphIsomorphismIndex    文件:SubgraphIsomorphismIndexImpl.java   
public Multimap<K,InsertPosition<K,G,V,T>> lookup(G queryGraph,boolean exactMatch) {

        Set<T> queryGraphTags = extractGraphTagsWrapper(queryGraph);

        Collection<InsertPosition<K,T>> positions = new LinkedList<>();
        findInsertPositions(positions,rootNode,queryGraph,queryGraphTags,HashBiMap.create(),true,exactMatch); //,writer);

        Multimap<K,T>> result = HashMultimap.create();
        logger.debug("Lookup result candidates: " + positions.size());
        for(InsertPosition<K,T> pos : positions) {
            // Match with the children

            result.put(pos.getNode().getKey(),pos);
            //System.out.println("Node " + pos.node + " with keys " + pos.node.getKeys() + " iso: " + pos.getGraphIso().getInToOut());
//            for(K key : pos.node.getKeys()) {
//                result.put(key,pos);
//            }
        }
        return result;
    }
项目:SubgraphIsomorphismIndex    文件:SubgraphIsomorphismIndexImpl.java   
/**
     * During the insert procedure,the insert graph is never renamed,because we want to figure out
     * how to remap existing nodes such they become a subgraph of the insertGraph.
     *
     * @param graph
     */
    void add(IndexNode<K,T> node,K key,G insertGraph,Set<T> insertGraphTags,BiMap<V,V> baseIso,boolean forceInsert) { //,IndentedWriter writer) {
        // The insert graph must be larger than the node Graph


        Collection<InsertPosition<K,T>> positions = new LinkedList<>();
        HashBiMap<V,V> deltaIso = HashBiMap.create();
        findInsertPositions(positions,node,insertGraph,insertGraphTags,baseIso,deltaIso,false,false); //,writer);

//        positions.forEach(p -> {
//            System.out.println("Insert pos: " + p.getNode().getKey() + " --- " + p.getIso());
//        });

        for(InsertPosition<K,T> pos : positions) {
            performAdd(key,pos,forceInsert); //,writer);
        }
    }
项目:cakes    文件:HashBiMapDemo.java   
/**
 * BiMap存储数据时出现冲突
 * 存储时,如果key相同,则会覆盖,则逆转后不会有问题
 * 存储时,如果key不同,value有相同,则逆转时会抛出异常IllegalArgumentException
 */
@Test
public void testConflictInsertKV() {
    // 存储相同key数据,此时会覆盖k1=v1
    BiMap<String,String> biMap1 = HashBiMap.create();
    biMap1.put("k1","v1");
    biMap1.put("k1","v2");
    System.out.println("biMap1: " + biMap1);

    // 获取的只有 v2=k1
    BiMap<String,String> inverseBiMap1 = biMap1.inverse();
    System.out.println("inverseBiMap1: " + inverseBiMap1);

    System.out.println("--------------------------------------");

    // 存储相同的value数据
    BiMap<String,String> biMap2 = HashBiMap.create();
    biMap2.put("k1","v1");

    // 此时抛出异常 java.lang.IllegalArgumentException: value already present: v1
    biMap2.put("k2","v1");
    System.out.println("biMap2: " + biMap2);

    BiMap<String,String> inverseBiMap2 = biMap2.inverse();
    System.out.println("inverseBiMap2: " + inverseBiMap2);
}
项目:cakes    文件:HashBiMapDemo.java   
/**
 * value如果有冲突时会抛异常,此时可以选择强制覆盖,forcePut
 */
@Test
public void testFixedConflict() {
    BiMap<String,String> biMap = HashBiMap.create();
    biMap.put("k1","v1");

    // 此时会强制覆盖,连原来的k1=v1都不存在
    biMap.forcePut("k2","v1");

    // biMap: {k2=v1}
    System.out.println("biMap2: " + biMap);

    BiMap<String,String> inverseBiMap = biMap.inverse();

    // inverseBiMap: {v1=k2}
    System.out.println("inverseBiMap: " + inverseBiMap);
}
项目:cakes    文件:HashBiMapDemo.java   
/**
 * HashBiMap key,value 相关校验
 */
@Test
public void testKeyValueCheck() {
    BiMap<String,"v1");

    // 校验 map 是否为空
    boolean isBiMapEmpty = biMap.isEmpty();
    System.out.println("isBiMapEmpty: " + isBiMapEmpty);

    // 检查某个key是否存在
    boolean isKeyExists = biMap.containsKey("k1");
    System.out.println("isKeyExists: " + isKeyExists);

    // 检查某个value是否存在
    boolean isValueExists = biMap.containsValue("v1");
    System.out.println("isValueExists: " + isValueExists);
}
项目:cakes    文件:HashBiMapDemo.java   
/**
 * HashBiMap 修改数据
 * putAll
 * remove
 * replace
 */
@Test
public void testUpdateBiMapDate() {
    BiMap<String,"v1");
    biMap.put("k2","v2");

    // putAll,存入另一个Map的数据,此时如果value有重复的依然会抛异常
    biMap.putAll(ImmutableBiMap.of("k3","v3","k4","v4","k5","v5","k6","v6"));
    System.out.println("biMap putAll after: " + biMap);

    System.out.println("\n-------------------------------------------\n");

    // remove,移除指定key的元素,如果key不存在,则返回null
    String v2 = biMap.remove("k2");
    String valueNotExists = biMap.remove("keyNotExists");
    System.out.println("remove k2 then biMap= " + biMap + ",and remove the value= " + v2);
    System.out.println("valueNotExists=" + valueNotExists);

    System.out.println("\n-------------------------------------------\n");

    // 清空map里的数据
    biMap.clear();
    System.out.println("clean biMap=" + biMap);
}
项目:CustomWorldGen    文件:GameData.java   
@SuppressWarnings("unchecked")
@Override
public void onCreate(Map<ResourceLocation,?> slaveset,BiMap<ResourceLocation,? extends IForgeRegistry<?>> registries)
{
    final ClearableObjectIntIdentityMap<IBlockState> idMap = new ClearableObjectIntIdentityMap<IBlockState>()
    {
        @SuppressWarnings("deprecation")
        @Override
        public int get(IBlockState key)
        {
            Integer integer = (Integer)this.identityMap.get(key);
            // There are some cases where this map is queried to serialize a state that is valid,//but somehow not in this list,so attempt to get real metadata. Doing this hear saves us 7 patches
            if (integer == null && key != null)
                integer = this.identityMap.get(key.getBlock().getStateFromMeta(key.getBlock().getMetaFromState(key)));
            return integer == null ? -1 : integer.intValue();
        }
    };
    ((Map<ResourceLocation,Object>)slaveset).put(BLOCKSTATE_TO_ID,idMap);
    final HashBiMap<Block,Item> map = HashBiMap.create();
    ((Map<ResourceLocation,Object>)slaveset).put(BLOCK_TO_ITEM,map);
}
项目:CustomWorldGen    文件:FluidRegistry.java   
public static Fluid lookupFluidForBlock(Block block)
{
    if (fluidBlocks == null)
    {
        BiMap<Block,Fluid> tmp = HashBiMap.create();
        for (Fluid fluid : fluids.values())
        {
            if (fluid.canBePlacedInWorld() && fluid.getBlock() != null)
            {
                tmp.put(fluid.getBlock(),fluid);
            }
        }
        fluidBlocks = tmp;
    }
    return fluidBlocks.get(block);
}
项目:CustomWorldGen    文件:FluidRegistry.java   
public static void loadFluidDefaults(NBTTagCompound tag)
{
    Set<String> defaults = Sets.newHashSet();
    if (tag.hasKey("DefaultFluidList",9))
    {
        FMLLog.getLogger().log(Level.DEBUG,"Loading persistent fluid defaults from world");
        NBTTagList tl = tag.getTagList("DefaultFluidList",8);
        for (int i = 0; i < tl.tagCount(); i++)
        {
            defaults.add(tl.getStringTagAt(i));
        }
    }
    else
    {
        FMLLog.getLogger().log(Level.DEBUG,"World is missing persistent fluid defaults - using local defaults");
    }
    loadFluidDefaults(HashBiMap.create(fluidIDs),defaults);
}
项目:canal_mysql_elasticsearch_sync    文件:MappingServiceImpl.java   
@Override
public void afterPropertiesSet() throws Exception {
    dbEsBiMapping = HashBiMap.create();
    dbEsMapping.forEach((key,value) -> {
        String[] keyStrings = StringUtils.split(key,".");
        String[] valueStrings = StringUtils.split(value,".");
        dbEsBiMapping.put(new DatabaseTableModel(keyStrings[0],keyStrings[1]),new IndexTypeModel(valueStrings[0],valueStrings[1]));
    });

    mysqlTypeElasticsearchTypeMapping = Maps.newHashMap();
    mysqlTypeElasticsearchTypeMapping.put("char",data -> data);
    mysqlTypeElasticsearchTypeMapping.put("text",data -> data);
    mysqlTypeElasticsearchTypeMapping.put("blob",data -> data);
    mysqlTypeElasticsearchTypeMapping.put("int",Long::valueOf);
    mysqlTypeElasticsearchTypeMapping.put("date",data -> LocalDateTime.parse(data,formatter));
    mysqlTypeElasticsearchTypeMapping.put("time",formatter));
    mysqlTypeElasticsearchTypeMapping.put("float",Double::valueOf);
    mysqlTypeElasticsearchTypeMapping.put("double",Double::valueOf);
    mysqlTypeElasticsearchTypeMapping.put("decimal",Double::valueOf);
}
项目:jaf-examples    文件:StreamExamples.java   
public static void main(String[] args) throws IOException {
    List<Salary> list = SalaryFileUtils.readFromFile();

    long start = System.currentTimeMillis();
    HashBiMap<String,LongSummaryStatistics> groupMap = list.parallelStream()
        .filter(s -> s.getTotalIncome() > 100000)
        .collect(
            Collectors.groupingBy(
                Salary::namePrefix,() -> HashBiMap.create(),Collectors.summarizingLong(Salary::getTotalIncome)
            )
        );

    groupMap.values()
        .parallelStream()
        .sorted(Comparator.comparingLong(LongSummaryStatistics::getSum).reversed()) // 默认是从小到大排序
        .limit(10)
        .forEachOrdered(ls -> {
            System.out.format("[%s],count: %s,sum: %s \n",groupMap.inverse().get(ls),ls.getCount(),ls.getSum());
        });
    System.out.println("elapsed time : " + (System.currentTimeMillis() - start));
}
项目:ipst    文件:EurostagFakeNodes.java   
public static EurostagFakeNodes build(Network network,EurostagEchExportConfig config) {
    Objects.requireNonNull(network);
    Objects.requireNonNull(config);

    BiMap<String,String> fakeNodesMap = HashBiMap.create(new HashMap<>());
    AtomicLongMap<String> countUsesMap = AtomicLongMap.create();

    //adds 2 default fake nodes
    fakeNodesMap.put(EchUtil.FAKE_NODE_NAME1,EchUtil.FAKE_NODE_NAME1);
    countUsesMap.getAndIncrement(EchUtil.FAKE_NODE_NAME1);
    fakeNodesMap.put(EchUtil.FAKE_NODE_NAME2,EchUtil.FAKE_NODE_NAME2);
    countUsesMap.getAndIncrement(EchUtil.FAKE_NODE_NAME2);

    Identifiables.sort(network.getVoltageLevels()).stream().map(VoltageLevel::getId).forEach(vlId ->
            fakeNodesMap.put(vlId,newEsgId(fakeNodesMap,vlId)));

    return new EurostagFakeNodes(fakeNodesMap,countUsesMap,network);
}
项目:TRHS_Club_Mod_2016    文件:FluidRegistry.java   
public static Fluid lookupFluidForBlock(Block block)
{
    if (fluidBlocks == null)
    {
        BiMap<Block,fluid);
            }
        }
        fluidBlocks = tmp;
    }
    return fluidBlocks.get(block);
}
项目:TRHS_Club_Mod_2016    文件:FluidRegistry.java   
public static void loadFluidDefaults(NBTTagCompound tag)
{
    Set<String> defaults = Sets.newHashSet();
    if (tag.func_150297_b("DefaultFluidList","Loading persistent fluid defaults from world");
        NBTTagList tl = tag.func_150295_c("DefaultFluidList",8);
        for (int i = 0; i < tl.func_74745_c(); i++)
        {
            defaults.add(tl.func_150307_f(i));
        }
    }
    else
    {
        FMLLog.getLogger().log(Level.DEBUG,defaults);
}
项目:WikiParser    文件:WikiCSVWriter.java   
public static void write(ArticlesIdsRelations articlesIds,String file,String[] header)
{
    List<String[]> entries = new ArrayList<>();
    entries.add(header);
    HashBiMap<String,String> titleIdMap = articlesIds.getTitleIdMap();
    for (Map.Entry<String,String> e : titleIdMap.entrySet())
    {
        String id1 = e.getValue();
        String id2 = e.getKey();
        String[] entry =
        {
            id1,id2
        };
        entries.add(entry);
    }
    write(entries,file);

}
项目:asglogic    文件:Netlist.java   
public Netlist(BDDFactory fac,StateGraph sg,Reset reset) {
    this.fac = fac;
    this.reset = reset;
    this.nameVarMap = new HashMap<>();
    this.idVarMap = new HashMap<>();
    this.terms = new TreeMap<>(new BDDComparator());
    this.unmappedTerms = new HashSet<>();
    this.mappedTerms = new HashMap<>();
    this.quasiSignals = new HashMap<>();
    this.tmpid = 0;

    this.sigVarMap = HashBiMap.create();
    for(Signal sig : sg.getAllSignals()) {
        sigVarMap.put(sig,getNetlistVariableByName(sig.getName()));
    }

    initReset();
}
项目:ExoMagica    文件:RitualHandler.java   
public static void registerRitual(IRitual ritual,String name) {
    if(Strings.isNullOrEmpty(name)) {
        throw new IllegalArgumentException("Attempted to register a ritual with no name: " + ritual);
    }
    if(ritual == null) {
        throw new NullPointerException("The ritual cannot be null");
    }

    ModContainer mod = Loader.instance().activeModContainer();
    if(mod == null) {
        name = "minecraft:" + name;
    } else {
        name = mod.getModId() + ":" + name;
    }
    HashBiMap<String,IRitualRecipe> recipes = HashBiMap.create();
    NAMED_RITUALS.put(name,ritual);
    RITUALS_RECIPES.put(ritual,recipes);
}
项目:registry    文件:SchemaBranchCache.java   
public SchemaBranchCache(Integer size,Long expiryInSecs,final SchemaBranchFetcher schemaBranchFetcher) {
    schemaBranchNameToIdMap = Maps.synchronizedBiMap(HashBiMap.create());
    loadingCache = CacheBuilder.newBuilder()
            .maximumSize(size)
            .expireAfterAccess(expiryInSecs,TimeUnit.SECONDS)
            .build(new CacheLoader<Key,SchemaBranch>() {
                @Override
                public SchemaBranch load(Key key) throws Exception {
                    SchemaBranch schemaBranch;
                    Key otherKey;
                    if (key.getSchemaBranchKey() != null) {
                        schemaBranch = schemaBranchFetcher.getSchemaBranch(key.getSchemaBranchKey());
                        otherKey = Key.of(schemaBranch.getId());
                        schemaBranchNameToIdMap.put(key.getSchemaBranchKey(),schemaBranch.getId());
                    } else if (key.getId() != null) {
                        schemaBranch = schemaBranchFetcher.getSchemaBranch(key.getId());
                        otherKey = Key.of(new SchemaBranchKey(schemaBranch.getName(),schemaBranch.getSchemaMetadataName()));
                        schemaBranchNameToIdMap.put(otherKey.schemaBranchKey,schemaBranch.getId());
                    } else {
                        throw new IllegalArgumentException("Given argument is not valid: " + key);
                    }
                    loadingCache.put(otherKey,schemaBranch);
                    return schemaBranch;
                }
            });
}
项目:jamocha    文件:ECSetRuleBuilder.java   
public ConstructCache.Defrule.ECSetRule build() {
    if (1 != this.stack.size()) {
        throw new IllegalStateException("Rule can only be constructed if all existential scopes are closed!");
    }
    final AbstractConditionProxy conditionProxy = this.stack.pop();
    final Set<ECFilterSet> condition = conditionProxy.condition;
    final Set<SingleFactVariable> factVariableSet = conditionProxy.factVariableSet;
    final Set<RuleCondition.EquivalenceClass> equivalenceClasses = conditionProxy.equivalenceClasses;
    equivalenceClasses.addAll(this.constantToEquivalenceClass.values());
    final Set<RuleCondition.EquivalenceClass> usedECs = ECCollector.collect(condition);
    if (usedECs.contains(this.initialFactVariable.getEqual())) {
        factVariableSet.add(this.initialFactVariable);
        equivalenceClasses.add(this.initialFactVariable.getEqual());
    }
    final ConstructCache.Defrule defrule =
            new ConstructCache.Defrule(this.ruleName,null,ImmutableList.of());
    final ConstructCache.Defrule.ECSetRule ecSetRule =
            defrule.newECSetRule(condition,factVariableSet,equivalenceClasses,HashBiMap.create(0),0);
    return ecSetRule;
}
项目:api-compiler    文件:RestAnalyzer.java   
private static ImmutableMap<String,Map<CollectionAttribute,String>> generateShortNames(
    Collection<CollectionAttribute> collections) {
  // Map[version -> Map[name -> collection]] because collection name must be unique within a
  // given version,but likely is not unique across versions.
  Map<String,BiMap<String,CollectionAttribute>> versionMap = new HashMap<>();
  for (CollectionAttribute collection : collections) {
    String version = collection.getVersionWithDefault();
    if (!versionMap.containsKey(version)) {
      versionMap.put(version,HashBiMap.<String,CollectionAttribute>create());
    }
    String baseName = collection.getBaseName();
    String shortName = baseName.substring(baseName.lastIndexOf(".") + 1);
    insertOrDisambiguate(versionMap.get(version),shortName,collection);
  }

  ImmutableMap.Builder<String,String>> shortNames =
      new ImmutableMap.Builder<>();
  for (Map.Entry<String,CollectionAttribute>> entry : versionMap.entrySet()) {
    shortNames.put(entry.getKey(),entry.getValue().inverse());
  }
  return shortNames.build();
}
项目:SilverKing    文件:AsyncKeyedOperationImpl.java   
public AsyncKeyedOperationImpl(KeyedNamespaceOperation<K> operation,KeyCreator<K> keyCreator,ClientNamespace namespace,long curTime,byte[] originator) {
    super(operation,namespace.getContext(),curTime,originator);

    this.keyedNamespaceOperation = (KeyedNamespaceOperation<K>)operation;
    size = keyedNamespaceOperation.size();
    this.keyCreator = keyCreator;
    //dhtKeyToKey = new Object2ObjectOpenHashMap<>(size);
    //keyToDHTKey = new Object2ObjectOpenHashMap<>(size);
    //dhtKeyToKey = new HashMap<>(size);
    //keyToDHTKey = new HashMap<>(size);
    if (size != 1) {
     keyDHTKeyBiMap = HashBiMap.create(size);
     keyToDHTKey = keyDHTKeyBiMap;
     dhtKeyToKey = keyDHTKeyBiMap.inverse();
    } else {
     keyDHTKeyBiMap = null;
     keyToDHTKey = new SingleKeyToDHTKeyMap<>();
     dhtKeyToKey = new SingleDHTKeyToKeyMap<>();
    }
    dhtKeys = createKeys(keyCreator);
    failureCausesRef = new AtomicReference<>();
    resultsReceived = new AtomicInteger();
    completionCheckLock = new SpinLock();
    //completionCheckLock = new ReentrantLock();
}
项目:copybara    文件:TodoReplace.java   
@Override
public Transformation reverse() throws NonReversibleValidationException {
  if (mode != Mode.MAP_OR_FAIL && mode != Mode.MAP_OR_IGNORE) {
    throw new NonReversibleValidationException(location,mode + " mode is not reversible");
  }

  BiMap<String,String> mapping;
  try {
    mapping = HashBiMap.create(this.mapping);
  } catch (IllegalArgumentException e) {
    throw new NonReversibleValidationException(location,"Non-reversible mapping: " + e.getMessage());
  }

  return new TodoReplace(location,glob,todoTags,mode,mapping.inverse(),defaultString,parallelizer);
}
项目:FastDMM    文件:DMM.java   
public void expandKeys() {
    keyLen++;
    Set<String> unusedKeysSet = new TreeSet<>();
    generateKeys(keyLen,unusedKeysSet);
    ArrayList<String> newUnusedKeys = new ArrayList<>(unusedKeysSet);
    BiMap<String,TileInstance> newInstances = HashBiMap.create();
    Map<Location,String> newMap = new HashMap<>();
    Map<String,String> substitutions = new HashMap<>();
    for(Map.Entry<String,TileInstance> instance : instances.entrySet()) {
        String newKey = newUnusedKeys.get(rand.nextInt(newUnusedKeys.size()));
        newUnusedKeys.remove(newKey);
        substitutions.put(instance.getKey(),newKey);
        newInstances.put(newKey,instance.getValue());
    }
    for(Map.Entry<Location,String> mapInst : map.entrySet()) {
        newMap.put(mapInst.getKey(),substitutions.get(mapInst.getValue()));
    }

    diffStack.push(new DMMDiff.ExpandKeysDiff(this,newMap,instances,newInstances,unusedKeys,newUnusedKeys,keyLen-1,keyLen));
    instances = newInstances;
    map = newMap;
    unusedKeys = newUnusedKeys;
}
项目:CustomItemLibrary    文件:DurabilityRegistry.java   
public void register(ItemType itemType,PluginContainer pluginContainer,Iterable<String> models,String modelDirectoryName) {
    models.forEach(model -> {
        BiMap<Integer,Identifier> durabilityToModelId = typeToDurabilityToModelId.computeIfAbsent(itemType,k -> HashBiMap.create());
        Identifier modelId = new Identifier(pluginContainer.getId(),model);

        // Is the model already registered? If so,skip.
        Integer registeredDurability = durabilityToModelId.inverse().get(modelId);

        if(registeredDurability == null) {
            registeredDurability = getAvailableDurability(itemType);
        }

        DurabilityIdentifier durabilityId = new DurabilityIdentifier(itemType,registeredDurability);

        durabilityIdToDirectoryName.put(durabilityId,modelDirectoryName);
        durabilityIdToModelId.put(durabilityId,modelId);
        durabilityToModelId.put(registeredDurability,modelId);
    });
}
项目:fili    文件:SqlResultSetProcessor.java   
/**
 * Builds something to process a set of sql results and return them as the
 * same format as a GroupBy query to Druid.
 *
 * @param druidQuery  The original query that was converted to a sql query.
 * @param apiToFieldMapper  The mapping from api to physical name.
 * @param objectMapper  The mapper for all JSON processing.
 * @param sqlTimeConverter  The time converter used with making the query.
 */
public SqlResultSetProcessor(
        DruidAggregationQuery<?> druidQuery,ApiToFieldMapper apiToFieldMapper,ObjectMapper objectMapper,SqlTimeConverter sqlTimeConverter
) {
    this.druidQuery = druidQuery;
    this.apiToFieldMapper = apiToFieldMapper;
    this.objectMapper = objectMapper;
    this.sqlTimeConverter = sqlTimeConverter;

    this.sqlResults = new ArrayList<>();
    this.columnToColumnName = HashBiMap.create();

    this.groupByDimensionsCount = druidQuery.getDimensions().size();
}
项目:dhis2-core    文件:DefaultValidationNotificationService.java   
private Map<Set<User>,NotificationMessage> createSingleNotifications( SortedSet<MessagePair> messagePairs )
{
    BiMap<Set<User>,NotificationMessage> singleNotificationCollection = HashBiMap.create();

    for ( MessagePair messagePair : messagePairs )
    {
        NotificationMessage notificationMessage = notificationMessageRenderer
            .render( messagePair.result,messagePair.template );

        notificationMessage.setPriority( getPriority( messagePair.result.getValidationRule().getImportance() ) );

        singleNotificationCollection.put( new HashSet<>(),notificationMessage );

        resolveRecipients( messagePair )
            .forEach( user -> singleNotificationCollection.inverse().get( notificationMessage ).add( user ) );
    }

    return singleNotificationCollection;
}
项目:dhis2-core    文件:DefaultValidationNotificationService.java   
private static Map<Set<User>,SortedSet<MessagePair>> groupRecipientsForMessagePairs(
    Map<User,SortedSet<MessagePair>> messagePairsPerUser )
{
    BiMap<Set<User>,SortedSet<MessagePair>> grouped = HashBiMap.create();

    for ( Map.Entry<User,SortedSet<MessagePair>> entry : messagePairsPerUser.entrySet() )
    {
        User user = entry.getKey();
        SortedSet<MessagePair> setOfPairs = entry.getValue();

        if ( grouped.containsValue( setOfPairs ) )
        {
            // Value exists -> Add user to the existing key set
            grouped.inverse().get( setOfPairs ).add( user );
        }
        else
        {
            // Value doesn't exist -> Add the [user,set] as a new entry
            grouped.put( Sets.newHashSet( user ),setOfPairs );
        }
    }

    return grouped;
}
项目:AppInventorRaspberryPiCompanion    文件:P1Header.java   
public P1Header() {
  pinConfiguration = HashBiMap.create();
  pinConfiguration.put(3,RaspiPin.GPIO_08);
  pinConfiguration.put(5,RaspiPin.GPIO_09);
  pinConfiguration.put(7,RaspiPin.GPIO_07);
  pinConfiguration.put(8,RaspiPin.GPIO_15);
  pinConfiguration.put(10,RaspiPin.GPIO_16);
  pinConfiguration.put(11,RaspiPin.GPIO_00);
  pinConfiguration.put(12,RaspiPin.GPIO_01);
  pinConfiguration.put(13,RaspiPin.GPIO_02);
  pinConfiguration.put(15,RaspiPin.GPIO_03);
  pinConfiguration.put(16,RaspiPin.GPIO_04);
  pinConfiguration.put(18,RaspiPin.GPIO_05);
  pinConfiguration.put(19,RaspiPin.GPIO_12);
  pinConfiguration.put(21,RaspiPin.GPIO_13);
  pinConfiguration.put(22,RaspiPin.GPIO_06);
  pinConfiguration.put(23,RaspiPin.GPIO_14);
  pinConfiguration.put(24,RaspiPin.GPIO_10);
  pinConfiguration.put(26,RaspiPin.GPIO_11);
}
项目:powsybl-core    文件:StringToIntMapper.java   
public StringToIntMapper(Class<S> clazz) {
    this.clazz = clazz;
    id2num = new EnumMap<>(clazz);
    counter = new EnumMap<>(clazz);
    for (S s : clazz.getEnumConstants()) {
        id2num.put(s,Integer>create());
        counter.put(s,s.getInitialValue());
    }
}
项目:powsybl-core    文件:StringToIntMapper.java   
public synchronized void reset(S subset) {
    if (subset == null) {
        throw new IllegalArgumentException("subset is null");
    }
    id2num.put(subset,Integer>create());
    counter.put(subset,subset.getInitialValue());
}
项目:r8    文件:DexBuilder.java   
private TryInfo computeTryInfo() {
  // Canonical map of handlers.
  BiMap<CatchHandlers<BasicBlock>,Integer> canonicalHandlers = HashBiMap.create();
  // Compute the list of try items and their handlers.
  List<TryItem> tryItems = computeTryItems(canonicalHandlers);
  // Compute handler sets before dex items which depend on the handler index.
  Try[] tries = getDexTryItems(tryItems,canonicalHandlers);
  TryHandler[] handlers = getDexTryHandlers(canonicalHandlers.inverse());
  return new TryInfo(tries,handlers);
}
项目:hadoop-oss    文件:ShellBasedIdMapping.java   
synchronized private void loadFullUserMap() throws IOException {
  BiMap<Integer,String> uMap = HashBiMap.create();
  if (OS.startsWith("Mac")) {
    updateMapInternal(uMap,"user",MAC_GET_ALL_USERS_CMD,"\\s+",staticMapping.uidMapping);
  } else {
    updateMapInternal(uMap,GET_ALL_USERS_CMD,":",staticMapping.uidMapping);
  }
  uidNameMap = uMap;
  lastUpdateTime = Time.monotonicNow();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


com.google.gson.internal.bind.ArrayTypeAdapter的实例源码
com.google.gson.JsonSyntaxException的实例源码
com.google.gson.JsonDeserializer的实例源码
com.google.gson.internal.ConstructorConstructor的实例源码
com.google.gson.JsonPrimitive的实例源码
com.google.gson.LongSerializationPolicy的实例源码
com.google.gson.internal.GsonInternalAccess的实例源码
com.google.gson.JsonIOException的实例源码
com.google.gson.internal.StringMap的实例源码
com.google.gson.JsonObject的实例源码
com.google.gson.internal.bind.TimeTypeAdapter的实例源码
com.google.gson.FieldAttributes的实例源码
com.google.gson.internal.bind.TreeTypeAdapter的实例源码
com.google.gson.internal.LinkedHashTreeMap的实例源码
com.google.gson.TypeAdapterFactory的实例源码
com.google.gson.JsonSerializer的实例源码
com.google.gson.FieldNamingPolicy的实例源码
com.google.gson.JsonElement的实例源码
com.google.gson.internal.JsonReaderInternalAccess的实例源码
com.google.gson.TypeAdapter的实例源码