Java Code Examples for java.util.Map.size()

The following are Jave code examples for showing how to use size() of the java.util.Map 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: stynico   File: Test.java   View Source Code Vote up 6 votes
public static String chanceSelect(Map<String, Integer> keyChanceMap) { 
    if(keyChanceMap == null || keyChanceMap.size() == 0)  
 return null;  

    Integer sum = 0;  
    for (Integer value : keyChanceMap.values()) {  
 sum += value;  
    }  
    // 从1开始  
    Integer rand = new Random().nextInt(sum) + 1;  

    for (Map.Entry<String, Integer> entry : keyChanceMap.entrySet()) {
        rand -= entry.getValue();
        // 选中
        if (rand <= 0) {
            String item = entry.getKey();
            return item;
        }
    } 

    return null;  
}
 
Example 2
Project: lams   File: FilterKey.java   View Source Code Vote up 6 votes
/**
 * Constructs a number of FilterKey instances, given the currently enabled filters
 *
 * @param enabledFilters The currently enabled filters
 *
 * @return The filter keys, one per enabled filter
 */
public static Set<FilterKey> createFilterKeys(Map<String,Filter> enabledFilters) {
	if ( enabledFilters.size() == 0 ) {
		return null;
	}
	final Set<FilterKey> result = new HashSet<FilterKey>();
	for ( Filter filter : enabledFilters.values() ) {
		final FilterKey key = new FilterKey(
				filter.getName(),
				( (FilterImpl) filter ).getParameters(),
				filter.getFilterDefinition().getParameterTypes()
		);
		result.add( key );
	}
	return result;
}
 
Example 3
Project: dubbo2   File: StringUtils.java   View Source Code Vote up 6 votes
public static String toQueryString(Map<String, String> ps) {
	StringBuilder buf = new StringBuilder();
	if (ps != null && ps.size() > 0) {
		for (Map.Entry<String, String> entry : new TreeMap<String, String>(ps).entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			if (key != null && key.length() > 0
					&& value != null && value.length() > 0) {
				if (buf.length() > 0) {
					buf.append("&");
				}
				buf.append(key);
				buf.append("=");
				buf.append(value);
			}
		}
	}
	return buf.toString();
}
 
Example 4
Project: java-velocypack   File: VPackSerializeDeserializeTest.java   View Source Code Vote up 6 votes
@Test
public void directFromObjectMap() throws VPackException {
	final Map<TestEntityString, TestEntityString> map = new HashMap<VPackSerializeDeserializeTest.TestEntityString, VPackSerializeDeserializeTest.TestEntityString>();
	map.put(new TestEntityString(), new TestEntityString());
	map.put(new TestEntityString(), new TestEntityString());

	final VPackSlice vpack = new VPack.Builder().build().serialize(map,
		new SerializeOptions().type(new Type<Map<TestEntityString, TestEntityString>>() {
		}.getType()));
	assertThat(vpack, is(notNullValue()));
	assertThat(vpack.isArray(), is(true));
	assertThat(vpack.getLength(), is(map.size()));
	for (int i = 0; i < map.size(); i++) {
		final VPackSlice entry = vpack.get(i);
		final VPackSlice key = entry.get("key");
		checkStringEntity(key);
		final VPackSlice value = entry.get("value");
		checkStringEntity(value);
	}
}
 
Example 5
Project: Tarski   File: AlloyUtilities.java   View Source Code Vote up 5 votes
public static int getTotalTargetCount(final IMarker marker) {
  final Map<IMarker, String> fieldsTargets = AlloyUtilities.getRelationsOfFirstSideMarker(marker);
  final ArrayList<IMarker> relationsTargets =
      AlloyUtilities.getTargetsOfMarkerAtRelations(marker);

  return fieldsTargets.size() + relationsTargets.size();
}
 
Example 6
Project: coteafs-services   File: RequestHandler.java   View Source Code Vote up 5 votes
/**
 * @author wasiq.bhamla
 * @since Sep 5, 2017 10:16:01 PM
 * @param parameters
 * @return instance
 */
public RequestHandler pathParams (final Map <String, Object> parameters) {
	if (parameters != null && parameters.size () > 0) {
		logMap ("Path Params", parameters);
		this.request = this.request.pathParams (parameters);
	}
	return this;
}
 
Example 7
Project: dubbocloud   File: UrlUtils.java   View Source Code Vote up 5 votes
public static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify) {
    if (notify != null && notify.size() > 0) {
        Map<String, Map<String, String>> newNotify = new HashMap<String, Map<String, String>>();
        for (Map.Entry<String, Map<String, String>> entry : notify.entrySet()) {
            String serviceName = entry.getKey();
            Map<String, String> serviceUrls = entry.getValue();
            if (!serviceName.contains(":") && !serviceName.contains("/")) {
                if (serviceUrls != null && serviceUrls.size() > 0) {
                    for (Map.Entry<String, String> entry2 : serviceUrls.entrySet()) {
                        String url = entry2.getKey();
                        String query = entry2.getValue();
                        Map<String, String> params = StringUtils.parseQueryString(query);
                        String group = params.get("group");
                        String version = params.get("version");
                        // params.remove("group");
                        // params.remove("version");
                        String name = serviceName;
                        if (group != null && group.length() > 0) {
                            name = group + "/" + name;
                        }
                        if (version != null && version.length() > 0) {
                            name = name + ":" + version;
                        }
                        Map<String, String> newUrls = newNotify.get(name);
                        if (newUrls == null) {
                            newUrls = new HashMap<String, String>();
                            newNotify.put(name, newUrls);
                        }
                        newUrls.put(url, StringUtils.toQueryString(params));
                    }
                }
            } else {
                newNotify.put(serviceName, serviceUrls);
            }
        }
        return newNotify;
    }
    return notify;
}
 
Example 8
Project: yacy_grid_mcp   File: ElasticsearchClient.java   View Source Code Vote up 5 votes
/**
 * Delete a list of documents for a given set of ids
 * ATTENTION: read about the time-out of version number checking in the method above.
 * 
 * @param ids
 *            a map from the unique identifier of a document to the document type
 * @return the number of deleted documents
 */
public int deleteBulk(String indexName, Map<String, String> ids) {
    // bulk-delete the ids
    if (ids == null || ids.size() == 0) return 0;
    BulkRequestBuilder bulkRequest = elasticsearchClient.prepareBulk();
    for (Map.Entry<String, String> id : ids.entrySet()) {
        bulkRequest.add(new DeleteRequest().id(id.getKey()).index(indexName).type(id.getValue()));
    }
    bulkRequest.execute().actionGet();
    return ids.size();
}
 
Example 9
Project: java-debug   File: VariableFormatter.java   View Source Code Vote up 5 votes
/**
 * Get the default options for all formatters registered.
 * @return The default options.
 */
@Override
public Map<String, Object> getDefaultOptions() {
    Map<String, Object> defaultOptions = new HashMap<>();
    int count1 = valueFormatterMap.keySet().stream().mapToInt(
        formatter -> this.mergeDefaultOptions(formatter, defaultOptions)).sum();
    int count2 = typeFormatterMap.keySet().stream().mapToInt(
        formatter -> this.mergeDefaultOptions(formatter, defaultOptions)).sum();
    if (count1 + count2 != defaultOptions.size()) {
        throw new IllegalStateException("There is some configuration conflicts on type and value formatters.");
    }
    return defaultOptions;
}
 
Example 10
Project: localcloud_fe   File: PluginResultHelper.java   View Source Code Vote up 5 votes
public static PluginResult createPluginResult(String actionName, Map<String, Object> data, ChcpError error) {
    JsonNode errorNode = null;
    JsonNode dataNode = null;

    if (error != null) {
        errorNode = createErrorNode(error.getErrorCode(), error.getErrorDescription());
    }

    if (data != null && data.size() > 0) {
        dataNode = createDataNode(data);
    }

    return getResult(actionName, dataNode, errorNode);
}
 
Example 11
Project: openjdk-jdk10   File: ModuleDescriptor.java   View Source Code Vote up 5 votes
private static <K,V> Map<K,V> emptyOrUnmodifiableMap(Map<K,V> map) {
    if (map.isEmpty()) {
        return Collections.emptyMap();
    } else if (map.size() == 1) {
        Map.Entry<K, V> entry = map.entrySet().iterator().next();
        return Collections.singletonMap(entry.getKey(), entry.getValue());
    } else {
        return Collections.unmodifiableMap(map);
    }
}
 
Example 12
Project: neoscada   File: AbstractStateMonitor.java   View Source Code Vote up 5 votes
protected synchronized void setStringAttributes ( final Map<String, String> attributes )
{
    final Map<String, Variant> convertedAttributes = new HashMap<String, Variant> ( attributes.size () );

    for ( final Map.Entry<String, String> entry : attributes.entrySet () )
    {
        convertedAttributes.put ( entry.getKey (), Variant.valueOf ( entry.getValue () ) );
    }

    setAttributes ( convertedAttributes );
}
 
Example 13
Project: azure-maven-plugins   File: PackageMojo.java   View Source Code Vote up 5 votes
protected Map<String, FunctionConfiguration> getFunctionConfigurations(final AnnotationHandler handler,
                                                                       final Set<Method> methods) throws Exception {
    info("");
    info(GENERATE_CONFIG);
    final Map<String, FunctionConfiguration> configMap = handler.generateConfigurations(methods);
    if (configMap.size() == 0) {
        info(GENERATE_SKIP);
    } else {
        final String scriptFilePath = getScriptFilePath();
        configMap.values().forEach(config -> config.setScriptFile(scriptFilePath));
        info(GENERATE_DONE);
    }

    return configMap;
}
 
Example 14
Project: hadoop   File: ReplicaMap.java   View Source Code Vote up 5 votes
/**
 * Get the size of the map for given block pool
 * @param bpid block pool id
 * @return the number of replicas in the map
 */
int size(String bpid) {
  Map<Long, ReplicaInfo> m = null;
  synchronized(mutex) {
    m = map.get(bpid);
    return m != null ? m.size() : 0;
  }
}
 
Example 15
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: DuplicateMessageInfo.java   View Source Code Vote up 5 votes
private int getDuplicateMsgNum(Map<Integer, Integer> msgDupMap) {
    int msgDupNum = 0;
    for (int i = 0; i < msgDupMap.size(); i++) {
        msgDupNum += msgDupMap.get(i);
    }
    return msgDupNum;
}
 
Example 16
Project: quiz_helper   File: Utils.java   View Source Code Vote up 5 votes
public static long[] getMapKeyArray(Map<Long, String> map) {
    long[] keyArr = new long[map.size()];
    int i = 0;
    for (long id : map.keySet()) {
        keyArr[i] = id;
        i++;
    }
    return keyArr;
}
 
Example 17
Project: HCFCore   File: ClosureUtils.java   View Source Code Vote up 4 votes
/**
 * Create a new Closure that uses the input object as a key to find the
 * closure to call.
 * <p>
 * The Map consists of object keys and Closure values. A closure
 * is called if the input object equals the key. If there is no match, the
 * default closure is called. The default closure is set in the map
 * using a null key.
 *
 * @see org.apache.commons.collections4.functors.SwitchClosure
 *
 * @param <E>  the type that the closure acts on
 * @param objectsAndClosures  a map of objects to closures
 * @return the closure
 * @throws NullPointerException if the map is null
 * @throws NullPointerException if any closure in the map is null
 * @throws IllegalArgumentException if the map is empty
 */
@SuppressWarnings("unchecked")
public static <E> Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures) {
    if (objectsAndClosures == null) {
        throw new NullPointerException("The object and closure map must not be null");
    }
    final Closure<? super E> def = objectsAndClosures.remove(null);
    final int size = objectsAndClosures.size();
    final Closure<? super E>[] trs = new Closure[size];
    final Predicate<E>[] preds = new Predicate[size];
    int i = 0;
    for (final Map.Entry<? extends E, Closure<E>> entry : objectsAndClosures.entrySet()) {
        preds[i] = EqualPredicate.<E>equalPredicate(entry.getKey());
        trs[i] = entry.getValue();
        i++;
    }
    return ClosureUtils.<E>switchClosure(preds, trs, def);
}
 
Example 18
Project: rapidminer   File: GeneratePredictionOperator.java   View Source Code Vote up 4 votes
@Override
public ExampleSet apply(ExampleSet exampleSet) throws OperatorException {
	// searching confidence attributes
	Map<Attribute, String> confidenceAttributes = new HashMap<Attribute, String>();
	for (Iterator<AttributeRole> iterator = exampleSet.getAttributes().specialAttributes(); iterator.hasNext();) {
		AttributeRole role = iterator.next();
		if (role.getSpecialName().matches(Attributes.CONFIDENCE_NAME + "_.*")) {
			confidenceAttributes.put(role.getAttribute(),
					role.getSpecialName().replaceAll("^" + Attributes.CONFIDENCE_NAME + "_(.*)$", "$1"));
		}
	}

	if (confidenceAttributes.size() > 0) {
		String predictionName = getParameterAsString(PARAMETER_PREDICTION_NAME);
		String attributeName = "prediction(" + predictionName + ")";
		Attribute predictionAttribute = AttributeFactory.createAttribute(attributeName, Ontology.NOMINAL);

		// check if an attribute with the resulting name already exists
		Attribute oldAttribute = exampleSet.getAttributes().get(attributeName);
		if (oldAttribute != null) {
			if (exampleSet.getAttributes().getSpecial(Attributes.PREDICTION_NAME) == oldAttribute) {
				// remove it iff it is the prediction attribute (since it would be removed later
				// anyway, but causes an error if not removed here)
				exampleSet.getAttributes().remove(oldAttribute);
			} else {
				// otherwise throw an error
				throw new UserError(this, 152, attributeName);
			}
		}

		for (String value : confidenceAttributes.values()) {
			predictionAttribute.getMapping().mapString(value);
		}
		exampleSet.getExampleTable().addAttribute(predictionAttribute);
		exampleSet.getAttributes().addRegular(predictionAttribute);
		exampleSet.getAttributes().setSpecialAttribute(predictionAttribute, Attributes.PREDICTION_NAME);
		for (Example example : exampleSet) {
			ArrayList<Tupel<Double, String>> labelConfidences = new ArrayList<Tupel<Double, String>>(
					confidenceAttributes.size());
			for (Map.Entry<Attribute, String> entry : confidenceAttributes.entrySet()) {
				labelConfidences.add(new Tupel<Double, String>(example.getValue(entry.getKey()), entry.getValue()));
			}
			Collections.sort(labelConfidences);
			example.setValue(
					predictionAttribute,
					predictionAttribute.getMapping().mapString(
							labelConfidences.get(labelConfidences.size() - 1).getSecond()));
		}
	}

	return exampleSet;
}
 
Example 19
Project: lams   File: BestResponseTimeBalanceStrategy.java   View Source Code Vote up 4 votes
public ConnectionImpl pickConnection(LoadBalancedConnectionProxy proxy, List<String> configuredHosts, Map<String, ConnectionImpl> liveConnections,
        long[] responseTimes, int numRetries) throws SQLException {

    Map<String, Long> blackList = proxy.getGlobalBlacklist();

    SQLException ex = null;

    for (int attempts = 0; attempts < numRetries;) {
        long minResponseTime = Long.MAX_VALUE;

        int bestHostIndex = 0;

        // safety
        if (blackList.size() == configuredHosts.size()) {
            blackList = proxy.getGlobalBlacklist();
        }

        for (int i = 0; i < responseTimes.length; i++) {
            long candidateResponseTime = responseTimes[i];

            if (candidateResponseTime < minResponseTime && !blackList.containsKey(configuredHosts.get(i))) {
                if (candidateResponseTime == 0) {
                    bestHostIndex = i;

                    break;
                }

                bestHostIndex = i;
                minResponseTime = candidateResponseTime;
            }
        }

        String bestHost = configuredHosts.get(bestHostIndex);

        ConnectionImpl conn = liveConnections.get(bestHost);

        if (conn == null) {
            try {
                conn = proxy.createConnectionForHost(bestHost);
            } catch (SQLException sqlEx) {
                ex = sqlEx;

                if (proxy.shouldExceptionTriggerConnectionSwitch(sqlEx)) {
                    proxy.addToGlobalBlacklist(bestHost);
                    blackList.put(bestHost, null);

                    if (blackList.size() == configuredHosts.size()) {
                        attempts++;
                        try {
                            Thread.sleep(250);
                        } catch (InterruptedException e) {
                        }
                        blackList = proxy.getGlobalBlacklist(); // try again after a little bit
                    }

                    continue;
                }

                throw sqlEx;
            }
        }

        return conn;
    }

    if (ex != null) {
        throw ex;
    }

    return null; // we won't get here, compiler can't tell
}
 
Example 20
Project: javaide   File: MultiResourceFile.java   View Source Code Vote up 4 votes
@Override
public boolean hasResources(ResourceType type) {
    Map<String, ResourceValue> list = mResourceItems.get(type);
    return (list != null && list.size() > 0);
}