public static void main(String[] args) { // 注意BiMap的key和value都不能重复,否则inverse之后就不能保证键值一一对应了 BiMap<String, Integer> users = HashBiMap.create(); users.put("bandery", 10); users.put("ryan", 11); users.put("liuyan", 12); // 反转,key变成value,value变成key System.out.println(users.inverse().get(10)); // 会有异常,key和value都不能重复 // System.out.println(users.inverse().get(11)); // 异常,"bandery"已经存在 // users.put("bandery", 1); // 如果想插入的话,可以用forcePut强制插入,但在这之前会将相同的K或者V对应 // 的键值对删除 // 这样会把之前的bandery-10删除 users.forcePut("bandery", 13); // 这样会把之前的ryan-11和liuyan-12都删除 users.forcePut("ryan", 12); // 当然还有putAll方法 Map<String, Integer> toadd = HashBiMap.create(); toadd.put("aaa", 111111); toadd.put("bbb", 22222); users.putAll(toadd); }
@Test public void whenCreateBiMap_thenCreated() { final BiMap<String, Integer> words = HashBiMap.create(); words.put("First", 1); words.put("Second", 2); words.put("Third", 3); assertEquals(2, words.get("Second").intValue()); assertEquals("Third", words.inverse().get(3)); }
/** * It marks the expression identified by the reference name as <code>evaluated</code>. In * addition, it adds an EvanNode for the expression identified by the reference. * * @param referenceName The reference name to be marked as 'evaluated'. * @param evalNode EvalNode to be added. */ public void markAsEvaluated(String referenceName, EvalNode evalNode) throws PlanningException { String normalized = referenceName; int refId = nameToIdMap.get(normalized); evaluationStateMap.put(refId, true); idToEvalMap.put(refId, evalNode); String originalName = checkAndGetIfAliasedColumn(normalized); if (originalName != null) { aliasedColumnMap.put(originalName, normalized); } }
@Test public void testBiMap() { BiMap<String, String> dataMap = HashBiMap.create(); dataMap.put("number", "dea123"); dataMap.put("dataEntered", "10/10/2012"); dataMap.put("keyCode", "code00001"); dataMap.put("isActive", "true"); // key and value are both unique. dataMap.forcePut("isMember", "true"); Assert.assertEquals("dea123", dataMap.get("number")); BiMap<String, String> inverseMap = dataMap.inverse(); Assert.assertEquals("keyCode", inverseMap.get("code00001")); Assert.assertEquals("isMember", inverseMap.get("true")); }
@Override public boolean add(TravelingItem item) { if (delegate.containsValue(item)) return false; item.setContainer(container); delegate.put(item.id, item); return true; }
@Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { String request = packet.content().toString(CharsetUtil.UTF_8); if (logger.isDebugEnabled()) logger.debug("Sender " + packet.sender() + " sent request:" + request); if (!sessionList.inverse().containsKey(packet.sender())) { String session = UUID.randomUUID().toString(); String localAddress = ctx.channel().localAddress().toString(); String remoteAddress = ctx.channel().remoteAddress().toString(); SubscriptionManagerFactory.getInstance() .add(session, session, outputType, localAddress, remoteAddress); sessionList.put(session, packet.sender()); if (logger.isDebugEnabled()) logger.debug("Added Sender " + packet.sender() + ", session:" + session); ctx.channel() .writeAndFlush( new DatagramPacket( Unpooled.copiedBuffer( Util.getWelcomeMsg().toString() + "\r\n", CharsetUtil.UTF_8), packet.sender())); } Map<String, Object> headers = getHeaders(sessionList.inverse().get(packet.sender())); producer.sendBodyAndHeaders(request, headers); }
public void addBootstrapToken(Token token, InetAddress endpoint) { assert token != null; assert endpoint != null; lock.writeLock().lock(); try { InetAddress oldEndPoint = null; oldEndPoint = bootstrapTokens.get(token); if (oldEndPoint != null && !oldEndPoint.equals(endpoint)) throw new RuntimeException( "Bootstrap Token collision between " + oldEndPoint + " and " + endpoint + " (token " + token); oldEndPoint = tokenToEndPointMap.get(token); if (oldEndPoint != null && !oldEndPoint.equals(endpoint)) throw new RuntimeException( "Bootstrap Token collision between " + oldEndPoint + " and " + endpoint + " (token " + token); bootstrapTokens.inverse().remove(endpoint); bootstrapTokens.put(token, endpoint); } finally { lock.writeLock().unlock(); } }
// Task: create collection to translate Polish-English words in two ways public static void main(String[] args) { ENGLISH_WORD[] englishWords = ENGLISH_WORD.values(); String[] russianWords = {"jeden", "dwa", "trzy", "kula", "snieg"}; // Create Multiset BiMap<ENGLISH_WORD, String> biMap = EnumHashBiMap.create(ENGLISH_WORD.class); // Create English-Polish dictionary int i = 0; for (ENGLISH_WORD englishWord : englishWords) { biMap.put(englishWord, russianWords[i]); i++; } // Print count words System.out.println(biMap); // print {ONE=jeden, TWO=dwa, THREE=trzy, BALL=kula, SNOW=snieg} // Print all unique words System.out.println(biMap.keySet()); // print [ONE, TWO, THREE, BALL, SNOW] System.out.println(biMap.values()); // print [jeden, dwa, trzy, kula, snieg] // Print translate by words System.out.println("one = " + biMap.get(ENGLISH_WORD.ONE)); // print one = jeden System.out.println("two = " + biMap.get(ENGLISH_WORD.TWO)); // print two = dwa System.out.println("kula = " + biMap.inverse().get("kula")); // print kula = BALL System.out.println("snieg = " + biMap.inverse().get("snieg")); // print snieg = SNOW System.out.println("empty = " + biMap.get("empty")); // print empty = null // Print count word's pair System.out.println(biMap.size()); // print 5 }
public static BiMap<Combo, Integer> getComboTuneMap() { int mod = getAsciiTuneMods(); BiMap<Combo, Integer> map = HashBiMap.create(); for (Map.Entry<Integer, Integer> entry : getAsciTuneMap().entrySet()) { map.put(new Combo(mod, entry.getKey()), entry.getValue()); } return map; }
/** * Create a predicate with a name associated to it. If the same name is passed again to this * method, the old predicate will be returned (guaranteeing uniqueness of predicate<->name * mapping). * * @param pName An arbitary name for a predicate. * @return A region representing a predicate */ public Region createPredicate(String pName) { Region result = regionMap.get(pName); if (result == null) { result = delegate.createPredicate(); regionMap.put(pName, result); } return result; }
@Override public int enumerateLabel(String label) { if (!labelEnumeration.containsKey(label)) { labelEnumeration.put(label, nextLabel); nextLabel++; } return labelEnumeration.get(label); }
public static Explosive register(Explosive zhaPin) { if (!isRegistered(zhaPin)) { int nextID = maxID++; idToExplosiveMap.put(nextID, zhaPin); idToNameMap.put(nextID, zhaPin.getUnlocalizedName()); return zhaPin; } return null; }
/** * Register a SubTileEntity and makes it a mini flower. Also adds the recipe and returns it. * * @see BotaniaAPI#registerSubTile */ public static RecipeManaInfusion registerMiniSubTile( String key, Class<? extends SubTileEntity> subtileClass, String original) { registerSubTile(key, subtileClass); miniFlowers.put(original, key); RecipeMiniFlower recipe = new RecipeMiniFlower(key, original, 2500); manaInfusionRecipes.add(recipe); miniFlowerRecipes.add(recipe); return recipe; }
public void setString(int columnIndex, String value) { Integer reuseIndex = stringReferences.get(value); if (reuseIndex != null) { bufferSlice.setInt(getOffset(columnIndex), reuseIndex); } else { int index = stringReferences.size(); stringReferences.put(value, index); bufferSlice.setInt(getOffset(columnIndex), index); stringReferenceSize += value.length() * 2 + 4; // assuming size of char = size of byte * 2 + length } clearNull(columnIndex); }
/** {@inheritDoc} */ public BiMap<EObject, EObject> computeMatches( Collection<EObject> values1, Collection<EObject> values2) { BiMap<EObject, EObject> result = HashBiMap.create(); Map<Object, EObject> matchingElements = computeIds(values2); for (EObject obj : values1) { Object id1 = idFunction.apply(obj); EObject match = matchingElements.get(id1); if (match != null && values2.contains(match)) { result.put(obj, match); } } return result; }
public void updateNormalToken(Token token, InetAddress endpoint) { assert token != null; assert endpoint != null; lock.writeLock().lock(); try { bootstrapTokens.inverse().remove(endpoint); tokenToEndPointMap.inverse().remove(endpoint); if (!endpoint.equals(tokenToEndPointMap.put(token, endpoint))) { sortedTokens = sortTokens(); } leavingEndPoints.remove(endpoint); } finally { lock.writeLock().unlock(); } }
String storeAndGenerateId(T value) { checkArgument( value instanceof Serializable, "When using JPPF, instances of %s must implement Serializable, " + "found: '%s' of class: %s.", clazz, value, value.getClass()); final String id; if (configMap.containsKey(value)) { id = configMap.get(value); } else { id = prefix + idNum++; configMap.put(value, id); } return id; }
public String toFieldName(String cls, String viewedClass, BigInteger rNum) { if (referenceFields.get(cls) == null) { BiMap<String, String> bimap = HashBiMap.create(); referenceFields.put(cls, bimap); } BiMap<String, String> map = referenceFields.get(cls); String key = getKey(viewedClass, rNum); if (map.get(key) != null) return map.get(key); else { String optimalFieldName = Util.lowerFirst(Util.toJavaIdentifier(viewedClass)) + "_R" + rNum; String currentKey = map.inverse().get(optimalFieldName); String fieldName; if (currentKey == null) fieldName = optimalFieldName; else fieldName = optimalFieldName + "_R" + rNum; map.put(key, fieldName); return fieldName; } }
static { TRAVEL_MODE_IDS.put(TravelMode.BICYCLING, "bicycling"); TRAVEL_MODE_IDS.put(TravelMode.CAR, "car"); TRAVEL_MODE_IDS.put(TravelMode.PUBLIC_TRANSIT, "publicTransit"); TRAVEL_MODE_IDS.put(TravelMode.WALKING, "walking"); TRAVEL_MODES.put(TravelMode.BICYCLING, "bicycling"); TRAVEL_MODES.put(TravelMode.CAR, "driving"); TRAVEL_MODES.put(TravelMode.PUBLIC_TRANSIT, "transit"); TRAVEL_MODES.put(TravelMode.WALKING, "walking"); ROUTE_DESCRIPTIONS.put(TravelMode.BICYCLING, "by bicycle"); ROUTE_DESCRIPTIONS.put(TravelMode.CAR, "by car"); ROUTE_DESCRIPTIONS.put(TravelMode.PUBLIC_TRANSIT, "by public transit"); ROUTE_DESCRIPTIONS.put(TravelMode.WALKING, "walking"); SUBROUTE_DESCRIPTIONS.put(TravelMode.BICYCLING, "Bicycling"); SUBROUTE_DESCRIPTIONS.put(TravelMode.CAR, "Car"); SUBROUTE_DESCRIPTIONS.put(TravelMode.PUBLIC_TRANSIT, "Public transit"); SUBROUTE_DESCRIPTIONS.put(TravelMode.WALKING, "Walking"); }
public void addSkill(Class<? extends SkillTreeSkill> skillClass) { if (!isValidSkill(skillClass)) { MyPetApi.getLogger().warning(ChatColor.RED + skillClass.getName() + " is not a valid skill!"); } try { Constructor<?> ctor = skillClass.getConstructor(boolean.class); Object obj = ctor.newInstance(false); if (obj instanceof SkillInstance) { SkillInstance skill = (SkillInstance) obj; String skillName = skill.getName(); skill.setMyPet(this.myPet); skillsNamesClass.put(skillName, skill); } } catch (Exception e) { MyPetApi.getLogger().warning(ChatColor.RED + skillClass.getName() + " is not a valid skill!"); e.printStackTrace(); registeredSkillsNames.remove(skillClass); } }
public static void main(String[] args) { BiMap<Integer, String> bm = HashBiMap.create(); bm.put(1, "s1"); bm.put(2, "s2"); System.out.println(bm.get(1)); System.out.println(bm.inverse().get("s1")); System.out.println(bm.getOrDefault(77, "s0")); // this throws and exception // bm.put(3, "s2"); // this forces the new mapping System.out.println(bm.get(2)); bm.forcePut(3, "s2"); System.out.println(bm.get(2)); System.out.println(bm.get(3)); System.out.println(bm.inverse().get("s2")); // after this key 2 is gone bm.forcePut(1, "s2"); System.out.println(bm); }
public String toFieldName(String cls, String attributeName) { if (referenceFields.get(cls) == null) { BiMap<String, String> bimap = HashBiMap.create(); referenceFields.put(cls, bimap); } BiMap<String, String> map = referenceFields.get(cls); String key = getKey(cls, attributeName); if (map.get(key) != null) return map.get(key); else { String optimalFieldName = Util.lowerFirst(Util.toJavaIdentifier(attributeName)); String fieldName = optimalFieldName; if (map.inverse().get(fieldName) != null) { int i = 1; while (map.inverse().get(fieldName + i) != null) { i++; } fieldName = fieldName + i; } map.put(key, fieldName); return fieldName; } }
public String toColumnName(String cls, String attributeName) { if (referencedColumns.get(cls) == null) { BiMap<String, String> bimap = HashBiMap.create(); referencedColumns.put(cls, bimap); } BiMap<String, String> map = referencedColumns.get(cls); String key = getKey(cls, attributeName); if (map.get(key) != null) return map.get(key); else { String optimalColumnName = Util.lowerFirst(Util.toColumnName(attributeName)); String columnName = optimalColumnName; if (map.inverse().get(columnName) != null || isReservedWord(columnName)) { int i = 1; while (map.inverse().get(columnName + "_" + i) != null) { i++; } columnName = columnName + "_" + i; } map.put(key, columnName); return columnName; } }
public String toTableName(String schema, String className) { if (referencedTables.get(schema) == null) { BiMap<String, String> bimap = HashBiMap.create(); referencedTables.put(schema, bimap); } BiMap<String, String> map = referencedTables.get(schema); String key = getKey(schema, className); if (map.get(key) != null) return map.get(key); else { String optimalName = Util.lowerFirst(Util.toColumnName(className)); String name = optimalName; if (map.inverse().get(name) != null || isReservedWord(name)) { int i = 1; while (map.inverse().get(name + "_" + i) != null) { i++; } name = name + "_" + i; } map.put(key, name); return name; } }
public void add(final BiMap<StringWrapper, UUID> toAdd) { if (uuidMap.size() == 0) { uuidMap = toAdd; } for (Map.Entry<StringWrapper, UUID> entry : toAdd.entrySet()) { UUID uuid = entry.getValue(); StringWrapper name = entry.getKey(); if ((uuid == null) || (name == null)) { continue; } BiMap<UUID, StringWrapper> inverse = uuidMap.inverse(); if (inverse.containsKey(uuid)) { if (uuidMap.containsKey(name)) { continue; } rename(uuid, name); continue; } uuidMap.put(name, uuid); } PS.debug(C.PREFIX.s() + "&6Cached a total of: " + uuidMap.size() + " UUIDs"); }
/** * Generates random squares for the pieces of the provided tablebase. * * @param tablebase computerized database containing all possible legal chess positions and their * evaluations, given the set of specific chess pieces * @return the bidirectional map from the pieces present in this chess position, to the squares * they occupy */ static BiMap<Piece, Square> generateRandomSquaresForPieces(Tablebase tablebase) { BiMap<Piece, Square> piecesWithSquares = EnumBiMap.create(Piece.class, Square.class); List<Piece> pieces = tablebase.getAllPieces(); MersenneTwisterFast numberGenerator = new MersenneTwisterFast(); Square randSquare = null; for (Piece piece : pieces) { do { if (piece.getPieceType() == PieceType.PAWN) { int pRand = numberGenerator.nextInt(Squares.PAWN_SQUARES.numberOfSquares()); randSquare = Squares.PAWN_SQUARES.getSquaresAsList().get(pRand); } else { int allRand = numberGenerator.nextInt(Squares.ALL_SQUARES.numberOfSquares()); randSquare = Squares.ALL_SQUARES.getSquaresAsList().get(allRand); } } while (piecesWithSquares.containsValue(randSquare)); piecesWithSquares.put(piece, randSquare); } return piecesWithSquares; }
/** * Adds an expression with an alias name and returns a reference name. It specifies the alias as * an reference name. */ public String addExpr(Expr expr, String alias) throws PlanningException { // if this name already exists, just returns the name. if (nameToIdMap.containsKey(alias)) { return alias; } // if the name is first int refId; if (idToExprBiMap.inverse().containsKey(expr)) { refId = idToExprBiMap.inverse().get(expr); } else { refId = getNextId(); idToExprBiMap.put(refId, expr); } nameToIdMap.put(alias, refId); evaluationStateMap.put(refId, false); // add the entry to idToNames map TUtil.putToNestedList(idToNamesMap, refId, alias); return alias; }
static { for (Suit s : Suit.values()) { sMap.put(s.ordinal(), s); } }
public Symbols(BytecodeCompleter bytecodeCompleter) { defaultPackage = new JavaSymbol.PackageJavaSymbol("", rootPackage); predefClass = new JavaSymbol.TypeJavaSymbol(Flags.PUBLIC, "", rootPackage); predefClass.members = new Scope(predefClass); ((JavaType.ClassJavaType) predefClass.type).interfaces = ImmutableList.of(); // TODO should have type "noType": noSymbol = new JavaSymbol.TypeJavaSymbol(0, "", rootPackage); methodClass = new JavaSymbol.TypeJavaSymbol(Flags.PUBLIC, "", noSymbol); // builtin types byteType = initType(JavaType.BYTE, "byte"); charType = initType(JavaType.CHAR, "char"); shortType = initType(JavaType.SHORT, "short"); intType = initType(JavaType.INT, "int"); longType = initType(JavaType.LONG, "long"); floatType = initType(JavaType.FLOAT, "float"); doubleType = initType(JavaType.DOUBLE, "double"); booleanType = initType(JavaType.BOOLEAN, "boolean"); nullType = initType(JavaType.BOT, "<nulltype>"); voidType = initType(JavaType.VOID, "void"); bytecodeCompleter.init(this); // predefined types for java lang JavaSymbol.PackageJavaSymbol javalang = bytecodeCompleter.enterPackage("java.lang"); // define a star import scope to let resolve types to java.lang when needed. javalang.members = new Scope.StarImportScope(javalang, bytecodeCompleter); javalang.members.enter(javalang); objectType = bytecodeCompleter.loadClass("java.lang.Object").type; classType = bytecodeCompleter.loadClass("java.lang.Class").type; stringType = bytecodeCompleter.loadClass("java.lang.String").type; cloneableType = bytecodeCompleter.loadClass("java.lang.Cloneable").type; serializableType = bytecodeCompleter.loadClass("java.io.Serializable").type; annotationType = bytecodeCompleter.loadClass("java.lang.annotation.Annotation").type; enumType = bytecodeCompleter.loadClass("java.lang.Enum").type; // Associate boxed types boxedTypes = HashBiMap.create(); boxedTypes.put(byteType, bytecodeCompleter.loadClass("java.lang.Byte").type); boxedTypes.put(charType, bytecodeCompleter.loadClass("java.lang.Character").type); boxedTypes.put(shortType, bytecodeCompleter.loadClass("java.lang.Short").type); boxedTypes.put(intType, bytecodeCompleter.loadClass("java.lang.Integer").type); boxedTypes.put(longType, bytecodeCompleter.loadClass("java.lang.Long").type); boxedTypes.put(floatType, bytecodeCompleter.loadClass("java.lang.Float").type); boxedTypes.put(doubleType, bytecodeCompleter.loadClass("java.lang.Double").type); boxedTypes.put(booleanType, bytecodeCompleter.loadClass("java.lang.Boolean").type); for (Entry<JavaType, JavaType> entry : boxedTypes.entrySet()) { entry.getKey().primitiveWrapperType = entry.getValue(); entry.getValue().primitiveType = entry.getKey(); } // TODO comment me arrayClass = new JavaSymbol.TypeJavaSymbol(Flags.PUBLIC, "Array", noSymbol); JavaType.ClassJavaType arrayClassType = (JavaType.ClassJavaType) arrayClass.type; arrayClassType.supertype = objectType; arrayClassType.interfaces = ImmutableList.of(cloneableType, serializableType); arrayClass.members = new Scope(arrayClass); arrayClass .members() .enter( new JavaSymbol.VariableJavaSymbol( Flags.PUBLIC | Flags.FINAL, "length", intType, arrayClass)); // TODO arrayClass implements clone() method enterOperators(); }
public void update() { Lifecycle serverState = getAttribute(Attributes.SERVICE_STATE_ACTUAL); if (Lifecycle.STOPPED.equals(serverState) || Lifecycle.STOPPING.equals(serverState) || Lifecycle.DESTROYED.equals(serverState) || !getAttribute(Attributes.SERVICE_UP)) { LOG.debug( "Skipped update of {} when service state is {} and running is {}", new Object[] { this, getAttribute(Attributes.SERVICE_STATE_ACTUAL), getAttribute(SERVICE_UP) }); return; } synchronized (this) { Iterable<Entity> availableEntities = FluentIterable.from(getEntities().getMembers()) .filter(new HasHostnameAndValidLifecycle()); LOG.debug("{} updating with entities: {}", this, Iterables.toString(availableEntities)); ImmutableListMultimap<String, Entity> hostnameToEntity = Multimaps.index(availableEntities, new HostnameTransformer()); Map<String, String> octetToName = Maps.newHashMap(); BiMap<String, String> ipToARecord = HashBiMap.create(); Multimap<String, String> aRecordToCnames = MultimapBuilder.hashKeys().hashSetValues().build(); Multimap<String, String> ipToAllNames = MultimapBuilder.hashKeys().hashSetValues().build(); for (Map.Entry<String, Entity> e : hostnameToEntity.entries()) { String domainName = e.getKey(); Maybe<SshMachineLocation> location = Machines.findUniqueSshMachineLocation(e.getValue().getLocations()); if (!location.isPresent()) { LOG.debug( "Member {} of {} does not have an SSH location so will not be configured", e.getValue(), this); continue; } else if (ipToARecord.inverse().containsKey(domainName)) { continue; } String address = location.get().getAddress().getHostAddress(); ipToAllNames.put(address, domainName); if (!ipToARecord.containsKey(address)) { ipToARecord.put(address, domainName); if (getReverseLookupNetwork().contains(new Cidr(address + "/32"))) { String octet = Iterables.get(Splitter.on('.').split(address), 3); if (!octetToName.containsKey(octet)) octetToName.put(octet, domainName); } } else { aRecordToCnames.put(ipToARecord.get(address), domainName); } } setAttribute(A_RECORDS, ImmutableMap.copyOf(ipToARecord.inverse())); setAttribute(PTR_RECORDS, ImmutableMap.copyOf(octetToName)); setAttribute(CNAME_RECORDS, Multimaps.unmodifiableMultimap(aRecordToCnames)); setAttribute(ADDRESS_MAPPINGS, Multimaps.unmodifiableMultimap(ipToAllNames)); // Update Bind configuration files and restart the service getDriver().updateBindConfiguration(); } }