Java Code Examples for java.util.HashMap.remove()

The following are Jave code examples for showing how to use remove() of the java.util.HashMap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GuancialeDB   File: delete.java   View Source Code Vote up 6 votes
@Usage("node-property <id> <key>")
@Named("node-property")
@Command
public void nodeProperty(InvocationContext<ObjectName> context,
                         @Usage("the node id") @Required @Argument final String id,
                         @Usage("the property key") @Required @Argument final String key) throws Exception {
    HashMap<String, Object> node = Server.db.getNode(id);
    if (node == null) {
        throw new Err(Status.NOT_FOUND);
    } else {
        node.remove(key);
        Server.db.updateNode(id, node);
        node = Server.db.getNode(id);
        context.append(mapper.writeValueAsString(node));
    }
}
 
Example 2
Project: GuancialeDB   File: delete.java   View Source Code Vote up 6 votes
@Usage("relationship-property <type> <from> <to> <key>")
@Named("relationship-property")
@Command
public void relationshipProperty(InvocationContext<ObjectName> context,
                                 @Usage("the relationship type") @Required @Argument final String type,
                                 @Usage("the starting node") @Required @Argument final String from,
                                 @Usage("the ending node") @Required @Argument final String to,
                                 @Usage("the property key") @Required @Argument final String key) throws Exception {
    HashMap<String, Object>  rel = Server.db.getRelationship(type, from, to);
    if (rel == null) {
        throw new Err(Status.NOT_FOUND);
    } else {
        rel.remove(key);
        Server.db.updateRelationship(type, from, to, rel);
        rel = Server.db.getRelationship(type, from, to);
        context.append(mapper.writeValueAsString(rel));
    }
}
 
Example 3
Project: metanome-algorithms   File: PLIBuilder.java   View Source Code Vote up 6 votes
protected static List<PositionListIndex> fetchPositionListIndexesStatic(List<HashMap<String, IntArrayList>> clusterMaps, boolean isNullEqualNull) {
	List<PositionListIndex> clustersPerAttribute = new ArrayList<>();
	for (int columnId = 0; columnId < clusterMaps.size(); columnId++) {
		List<IntArrayList> clusters = new ArrayList<>();
		HashMap<String, IntArrayList> clusterMap = clusterMaps.get(columnId);
		
		if (!isNullEqualNull)
			clusterMap.remove(null);
		
		for (IntArrayList cluster : clusterMap.values())
			if (cluster.size() > 1)
				clusters.add(cluster);
		
		clustersPerAttribute.add(new PositionListIndex(columnId, clusters));
	}
	return clustersPerAttribute;
}
 
Example 4
Project: enigma-vk   File: ConstPoolEditor.java   View Source Code Vote up 6 votes
@SuppressWarnings("rawtypes")
public void removeLastItem() {
	try {
		// remove the item from the cache
		HashMap cache = getCache();
		if (cache != null) {
			Object item = getItem(m_pool.getSize() - 1);
			cache.remove(item);
		}
		
		// remove the actual item
		// based off of LongVector.addElement()
		Object items = m_items.get(m_pool);
		Object[][] objects = (Object[][])m_objects.get(items);
		int numElements = (Integer)m_elements.get(items) - 1;
		int nth = numElements >> 7;
		int offset = numElements & (128 - 1);
		objects[nth][offset] = null;
		
		// decrement the number of items
		m_elements.set(items, numElements);
		m_numItems.set(m_pool, (Integer)m_numItems.get(m_pool) - 1);
	} catch (Exception ex) {
		throw new Error(ex);
	}
}
 
Example 5
Project: reading-and-annotate-rocketmq-3.4.6   File: KVConfigManager.java   View Source Code Vote up 6 votes
public void deleteKVConfig(final String namespace, final String key) {
    try {
        this.lock.writeLock().lockInterruptibly();
        try {
            HashMap<String, String> kvTable = this.configTable.get(namespace);
            if (null != kvTable) {
                String value = kvTable.remove(key);
                log.info("deleteKVConfig delete a config item, Namespace: {} Key: {} Value: {}", //
                    namespace, key, value);
            }
        }
        finally {
            this.lock.writeLock().unlock();
        }
    }
    catch (InterruptedException e) {
        log.error("deleteKVConfig InterruptedException", e);
    }

    this.persist();
}
 
Example 6
Project: oscm   File: ConfigurationBeanTest.java   View Source Code Vote up 6 votes
@Test
public void testGetItemsMissingValue() throws Exception {
    // Get test bean
    ConfigurationBean bean = getTestBean();

    // Remove one default value from controller settings
    HashMap<String, Setting> def_settings = platformService
            .getControllerSettings("ess.common",
                    new PasswordAuthentication("user", "password"));
    def_settings.remove(ControllerConfigurationKey.BSS_ORGANIZATION_ID
            .name());
    def_settings.remove("TEST1");
    platformService.storeControllerSettings("ess.common", def_settings,
            new PasswordAuthentication("user", "password"));

    // Get default items (missing value must be defined with an empty
    // string!)
    List<ConfigurationItem> items = bean.getAccessItems();
    assertNotNull(items);
    assertEquals(4, items.size());

    // Check the missing value
    ConfigurationItem item = findItem(items, "BSS_ORGANIZATION_ID");
    assertEquals("", item.getValue());
}
 
Example 7
Project: ACE_HackerRank   File: Solution.java   View Source Code Vote up 6 votes
public static void main(String[] args) {
    HashMap<Integer, Integer> map = new HashMap<>();
    ArrayDeque<Integer> deque     = new ArrayDeque<>();
    
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int m = scan.nextInt();
    int max = 0;
    
    for (int i = 0; i < n; i++) {
        /* Remove old value (if necessary) */
        if (i >= m) {
            int old = deque.removeFirst();
            if (map.get(old) == 1) {
                map.remove(old);
            } else {
                map.merge(old, -1, Integer::sum);
            }
        }
        
        /* Add new value */
        int num = scan.nextInt();
        deque.addLast(num);
        map.merge(num, 1, Integer::sum);
        
        max = Math.max(max, map.size());
    }
    
    scan.close();
    System.out.println(max);
}
 
Example 8
Project: sirocco   File: NonEnglishIndexer.java   View Source Code Vote up 6 votes
public CSList<TextTag> getTopTags(int nTags, HashMap<String,TextTag> tags) throws Exception {
    int resLen = nTags < tags.size() ? nTags : tags.size();
    CSList<TextTag> res = new CSList<TextTag>();
    String tag = null;
    float maxWeight;
    for (int i = 0;i < resLen;i++)
    {
        maxWeight = Float.MIN_VALUE;
        for (TextTag t : tags.values())
        {
            if (t.getWeight() > maxWeight)
            {
                tag = t.getWord();
                maxWeight = t.getWeight();
            }
             
        }
        res.add(new TextTag(tag, maxWeight, true));
        tags.remove(tag);
        if (res.size() > nTags)
            break;
         
    }
    return res;
}
 
Example 9
Project: lams   File: TokenProcessor.java   View Source Code Vote up 6 votes
/**
    * Reset the saved transaction token from request in the user's session.
    * 
    * @param request
    *            The servlet request
    */
   public synchronized void resetToken(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
    return;
}

HashMap tokens = getTokens(session);
if (tokens == null) {
    return;
}

String token = getTokenFromRequest(request);
if (token == null) {
    return;
}

tokens.remove(token);
   }
 
Example 10
Project: Logisim   File: AvoidanceMap.java   View Source Code Vote up 5 votes
public void markComponent(Component comp, int dx, int dy) {
	HashMap<Location, String> avoid = this.avoid;
	boolean translated = dx != 0 || dy != 0;
	Bounds bds = comp.getBounds();
	int x0 = bds.getX() + dx;
	int y0 = bds.getY() + dy;
	int x1 = x0 + bds.getWidth();
	int y1 = y0 + bds.getHeight();
	x0 += 9 - (x0 + 9) % 10;
	y0 += 9 - (y0 + 9) % 10;
	for (int x = x0; x <= x1; x += 10) {
		for (int y = y0; y <= y1; y += 10) {
			Location loc = Location.create(x, y);
			// loc is most likely in the component, so go ahead and
			// put it into the map as if it is - and in the rare event
			// that loc isn't in the component, we can remove it.
			String prev = avoid.put(loc, Connector.ALLOW_NEITHER);
			if (prev != Connector.ALLOW_NEITHER) {
				Location baseLoc = translated ? loc.translate(-dx, -dy) : loc;
				if (!comp.contains(baseLoc)) {
					if (prev == null) {
						avoid.remove(loc);
					} else {
						avoid.put(loc, prev);
					}
				}
			}
		}
	}
}
 
Example 11
Project: reading-and-annotate-rocketmq-3.4.6   File: ProducerManager.java   View Source Code Vote up 5 votes
public void unregisterProducer(final String group, final ClientChannelInfo clientChannelInfo) {
    try {
        if (this.groupChannelLock.tryLock(LockTimeoutMillis, TimeUnit.MILLISECONDS)) {
            try {
                HashMap<Channel, ClientChannelInfo> channelTable = this.groupChannelTable.get(group);
                if (null != channelTable && !channelTable.isEmpty()) {
                    ClientChannelInfo old = channelTable.remove(clientChannelInfo.getChannel());
                    if (old != null) {
                        log.info("unregister a producer[{}] from groupChannelTable {}", group,
                            clientChannelInfo.toString());
                    }

                    if (channelTable.isEmpty()) {
                        this.groupChannelTable.remove(group);
                        log.info("unregister a producer group[{}] from groupChannelTable", group);
                    }
                }
            }
            finally {
                this.groupChannelLock.unlock();
            }
        }
        else {
            log.warn("ProducerManager unregisterProducer lock timeout");
        }
    }
    catch (InterruptedException e) {
        log.error("", e);
    }
}
 
Example 12
Project: jdk8u-jdk   File: EnvHelp.java   View Source Code Vote up 5 votes
/**
 * Converts a map into a valid hash table, i.e.
 * it removes all the 'null' values from the map.
 */
public static <K, V> Hashtable<K, V> mapToHashtable(Map<K, V> map) {
    HashMap<K, V> m = new HashMap<K, V>(map);
    if (m.containsKey(null)) m.remove(null);
    for (Iterator<?> i = m.values().iterator(); i.hasNext(); )
        if (i.next() == null) i.remove();
    return new Hashtable<K, V>(m);
}
 
Example 13
Project: OpenJSharp   File: EnvHelp.java   View Source Code Vote up 5 votes
/**
 * Converts a map into a valid hash table, i.e.
 * it removes all the 'null' values from the map.
 */
public static <K, V> Hashtable<K, V> mapToHashtable(Map<K, V> map) {
    HashMap<K, V> m = new HashMap<K, V>(map);
    if (m.containsKey(null)) m.remove(null);
    for (Iterator<?> i = m.values().iterator(); i.hasNext(); )
        if (i.next() == null) i.remove();
    return new Hashtable<K, V>(m);
}
 
Example 14
Project: TextEmoji   File: OnekeyShare.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public void show(Context context) {
	HashMap<String, Object> shareParamsMap = new HashMap<String, Object>();
	shareParamsMap.putAll(params);

	MobSDK.init(context.getApplicationContext());
	ShareSDK.initSDK(context);

	// 打开分享菜单的统计
	ShareSDK.logDemoEvent(1, null);

	int iTheme = 0;
	try {
		iTheme = ResHelper.parseInt(String.valueOf(shareParamsMap.remove("theme")));
	} catch (Throwable t) {}
	OnekeyShareTheme theme = OnekeyShareTheme.fromValue(iTheme);
	OnekeyShareThemeImpl themeImpl = theme.getImpl();

	themeImpl.setShareParamsMap(shareParamsMap);
	themeImpl.setDialogMode(shareParamsMap.containsKey("dialogMode") ? ((Boolean) shareParamsMap.remove("dialogMode")) : false);
	themeImpl.setSilent(shareParamsMap.containsKey("silent") ? ((Boolean) shareParamsMap.remove("silent")) : false);
	themeImpl.setCustomerLogos((ArrayList<CustomerLogo>) shareParamsMap.remove("customers"));
	themeImpl.setHiddenPlatforms((HashMap<String, String>) shareParamsMap.remove("hiddenPlatforms"));
	themeImpl.setPlatformActionListener((PlatformActionListener) shareParamsMap.remove("callback"));
	themeImpl.setShareContentCustomizeCallback((ShareContentCustomizeCallback) shareParamsMap.remove("customizeCallback"));
	if (shareParamsMap.containsKey("disableSSO") ? ((Boolean) shareParamsMap.remove("disableSSO")) : false) {
		themeImpl.disableSSO();
	}

	themeImpl.show(context.getApplicationContext());
}
 
Example 15
Project: incubator-netbeans   File: ProxyLookup.java   View Source Code Vote up 5 votes
final <T> ImmutableInternalData removeTemplate(ProxyLookup proxy, Template<T> template) {
    if (getResults().containsKey(template)) {
        HashMap<Template,Reference<R>> c = new HashMap<Template, Reference<ProxyLookup.R>>(getResults());
        Reference<R> ref = c.remove(template);
        if (ref != null && ref.get() != null) {
            // seems like there is a reference to a result for this template
            // thta is still alive
            return this;
        }
        return create(getRawLookups(), c);
    } else {
        return this;
    }
}
 
Example 16
Project: openjdk-jdk10   File: SymbolTable.java   View Source Code Vote up 5 votes
public static void remove(Symbol symbol) {
    HashMap<Type, ArrayList<Symbol>> vars = SYMBOL_STACK.peek();
    if (vars.containsKey(symbol.type)) {
        ArrayList<Symbol> symbolsOfType = vars.get(symbol.type);
        symbolsOfType.remove(symbol);
        if (symbolsOfType.isEmpty()) {
            vars.remove(symbol.type);
        }
    }
}
 
Example 17
Project: monarch   File: PartitionedRegion.java   View Source Code Vote up 4 votes
/**
 * Fetches entries from local and remote nodes and appends these to register-interest response.
 */
public void fetchEntries(HashMap<Integer, HashSet> bucketKeys, VersionedObjectList values,
    ServerConnection servConn) throws IOException {
  int retryAttempts = calcRetry();
  RetryTimeKeeper retryTime = null;
  HashMap<Integer, HashSet> failures = new HashMap<Integer, HashSet>(bucketKeys);
  HashMap<InternalDistributedMember, HashMap<Integer, HashSet>> nodeToBuckets =
      new HashMap<InternalDistributedMember, HashMap<Integer, HashSet>>();

  while (--retryAttempts >= 0 && !failures.isEmpty()) {
    nodeToBuckets.clear();
    updateNodeToBucketMap(nodeToBuckets, failures);
    failures.clear();

    HashMap<Integer, HashSet> localBuckets = nodeToBuckets.remove(getMyId());
    if (localBuckets != null && !localBuckets.isEmpty()) {
      Set keys = new HashSet();
      for (Integer id : localBuckets.keySet()) {
        keys.addAll(localBuckets.get(id));
      }
      if (!keys.isEmpty()) {
        BaseCommand.appendNewRegisterInterestResponseChunkFromLocal(this, values, "keyList", keys,
            servConn);
      }
    }

    // Handle old nodes for Rolling Upgrade support
    Set<Integer> failedSet = handleOldNodes(nodeToBuckets, values, servConn);
    // Add failed buckets to nodeToBuckets map so that these will be tried on
    // remote nodes.
    if (!failedSet.isEmpty()) {
      for (Integer bId : failedSet) {
        failures.put(bId, bucketKeys.get(bId));
      }
      updateNodeToBucketMap(nodeToBuckets, failures);
      failures.clear();
    }

    fetchRemoteEntries(nodeToBuckets, failures, values, servConn);
    if (!failures.isEmpty()) {
      if (retryTime == null) {
        retryTime = new RetryTimeKeeper(this.retryTimeout);
      }
      if (!waitForFetchRemoteEntriesRetry(retryTime)) {
        break;
      }
    }
  }
  if (!failures.isEmpty()) {
    throw new InternalGemFireException("Failed to fetch entries from " + failures.size()
        + " buckets of region " + getName() + " for register interest.");
  }
}
 
Example 18
Project: incubator-netbeans   File: MeasureStartupTimeTestCase.java   View Source Code Vote up 4 votes
/**
 * Run IDE and read measured time from file
 *
 * @param performanceDataName name of the performance data
 * @param measureFile file where the time of window system painting is
 * stored
 * @param userdir userdir location
 * @param timeout wait after startup
 * @throws java.io.IOException
 * @return startup time
 */
protected long runIDEandMeasureStartup(String performanceDataName, File measureFile, File userdir, long timeout) throws IOException {

    try {
        long startTime = runIDE(getIdeHome(), userdir, measureFile, timeout);
        HashMap<String, Long> measuredValues = parseMeasuredValues(measureFile);

        Object tempValue = measuredValues.get("IDE starts t = ");
        long runTime = 0;
        long endTime = 0;
        if (!(tempValue == null)) {
            runTime = ((Long) tempValue).longValue(); // from STARTUP_DATA
            measuredValues.remove("IDE starts t = "); // remove from measured values, the rest we will log as performance data
        }
        tempValue = measuredValues.get("IDE is running t=");
        if (!(tempValue == null)) {
            endTime = ((Long) tempValue).longValue(); // from STARTUP_DATA
            measuredValues.remove("IDE is running t="); // remove from measured values, the rest we will log as performance data
        }

        long startupTime = endTime - startTime;

        System.out.println("\t" + startTime + " -> run from command line (start) ");
        System.out.println("\t" + runTime + " -> time from -Dorg.netbeans.log.startup.logfile - IDE starts (run)");
        System.out.println("\t" + endTime + " -> time from RepaintManager - IDE is running (end)");
        System.out.println("Measured Startup Time=" + startupTime + " / IDE run=" + (runTime - startTime));

        if (startupTime <= 0) {
            fail("Measured value [" + startupTime + "] is not > 0 !");
        }
        reportPerformance(performanceDataName + " | IDE run", runTime - startTime, "ms", 1);

        for (String[] data : STARTUP_DATA) {
            if (measuredValues.containsKey(data[1])) {
                long value = measuredValues.get(data[1]);
                System.out.println(data[0] + "=" + value);
                reportPerformance(performanceDataName + " | " + data[0], value, "ms", 1);
            } else {
                System.out.println("Value for " + data[1] + " isn't present");
            }
        }

        return startupTime;
    } catch (CantParseMeasuredValuesException ex) {
        Logger.getLogger(MeasureStartupTimeTestCase.class.getName()).log(Level.SEVERE, null, ex);
        throw new AssertionError(ex);
    }
}
 
Example 19
Project: asura   File: RAMJobStore.java   View Source Code Vote up 4 votes
private boolean removeTrigger(SchedulingContext ctxt, String triggerName,
        String groupName, boolean removeOrphanedJob) {
    String key = TriggerWrapper.getTriggerNameKey(triggerName, groupName);

    boolean found = false;

    synchronized (lock) {
        // remove from triggers by FQN map
        found = (triggersByFQN.remove(key) == null) ? false : true;
        if (found) {
            TriggerWrapper tw = null;
            // remove from triggers by group
            HashMap grpMap = (HashMap) triggersByGroup.get(groupName);
            if (grpMap != null) {
                grpMap.remove(triggerName);
                if (grpMap.size() == 0) {
                    triggersByGroup.remove(groupName);
                }
            }
            // remove from triggers array
            Iterator tgs = triggers.iterator();
            while (tgs.hasNext()) {
                tw = (TriggerWrapper) tgs.next();
                if (key.equals(tw.key)) {
                    tgs.remove();
                    break;
                }
            }
            timeTriggers.remove(tw);

            if (removeOrphanedJob) {
                JobWrapper jw = (JobWrapper) jobsByFQN.get(JobWrapper
                        .getJobNameKey(tw.trigger.getJobName(), tw.trigger
                                .getJobGroup()));
                Trigger[] trigs = getTriggersForJob(ctxt, tw.trigger
                        .getJobName(), tw.trigger.getJobGroup());
                if ((trigs == null || trigs.length == 0) && !jw.jobDetail.isDurable()) {
                    removeJob(ctxt, tw.trigger.getJobName(), tw.trigger
                            .getJobGroup());
                }
            }
        }
    }

    return found;
}
 
Example 20
Project: ExamensArbeteTD   File: AimingSystem.java   View Source Code Vote up 4 votes
private ArrayList<Entity> findNearestEnemies(Entity towerEntity) {

		Vector2 towerPosition = towerEntity.getComponent(PositionComponent.class).position;
		TargetComponent targetComp = Mappers.TARGET_M.get(towerEntity);

		if (getEngine().getEntitiesFor(Families.ENEMY) == null) {
			return null;
		}

		RangeComponent component = towerEntity.getComponent(RangeComponent.class);
		if (component == null) {
			return null;
		}
		Double range = component.getRange();

		ImmutableArray<Entity> enemies = getEngine().getEntitiesFor(Families.ENEMY);
		HashMap<Double, Entity> distanceMap = new HashMap<>();
		for (int i  = 0; i < enemies.size(); i++) {
			Vector2 enemyPosition = enemies.get(i).getComponent(PositionComponent.class).position;

			double distance = towerPosition.dst(enemyPosition);

			if (distance < range) {
				distanceMap.put(distance, enemies.get(i));
			}
		}
		if (distanceMap.isEmpty() || distanceMap.keySet().isEmpty()) {
			return null;
		}

		Map<Double, Entity> multiDistanceList = new HashMap<>();

		for (int i = 0; i < targetComp.getMaxTargets(); i++) {
			if (distanceMap.isEmpty() || distanceMap.keySet().isEmpty()) {
				break;
			}
			Double min = Collections.min(distanceMap.keySet());
			multiDistanceList.put(min, distanceMap.get(min));
			distanceMap.remove(min);
		}
		return new ArrayList<Entity>(multiDistanceList.values());

	}