Example usage for java.util Map keySet

List of usage examples for java.util Map keySet

Introduction

In this page you can find the example usage for java.util Map keySet.

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:com.google.appengine.tools.pipeline.impl.util.JsonUtils.java

private static String recursiveToString(Object y) {
    StringBuilder builder = new StringBuilder(512);
    if (null == y) {
        builder.append("null");
    } else {/*from w ww.  ja  v a 2 s  . c o m*/
        if (y instanceof List) {
            List<?> list = (List<?>) y;
            builder.append("(");
            boolean first = true;
            for (Object x : list) {
                if (!first) {
                    builder.append(", ");
                }
                builder.append(recursiveToString(x));
                first = false;
            }
            builder.append(")");
        } else if (y instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) y;
            builder.append("{");
            boolean first = true;
            for (Object key : map.keySet()) {
                if (!first) {
                    builder.append(", ");
                }
                builder.append(key);
                builder.append("=");
                builder.append(recursiveToString(map.get(key)));
                first = false;
            }
            builder.append("}");
        } else if (y instanceof String) {
            builder.append('"');
            builder.append(y);
            builder.append('"');
        } else {
            builder.append(y);
        }
    }
    return builder.toString();
}

From source file:de.tudarmstadt.ukp.dkpro.argumentation.sequence.report.ConfusionMatrixTools.java

public static String prettyPrintConfusionMatrixResults(ConfusionMatrix cm) {

    cm.printNiceResults();//w  ww. j  av  a2  s  .c o  m

    String f = "%.3f";

    List<String> header = new ArrayList<>();
    List<String> row = new ArrayList<>();

    header.add("Macro F1");
    header.add("Accuracy");
    header.add("Acc CI@95");

    row.add(String.format(Locale.ENGLISH, f, cm.getMacroFMeasure()));
    row.add(String.format(Locale.ENGLISH, f, cm.getAccuracy()));
    row.add(String.format(Locale.ENGLISH, f, cm.getConfidence95Accuracy()));

    Map<String, Double> precisionForLabels = cm.getPrecisionForLabels();
    Map<String, Double> recallForLabels = cm.getRecallForLabels();
    Map<String, Double> fMForLabels = cm.getFMeasureForLabels();

    SortedSet<String> labels = new TreeSet<>(precisionForLabels.keySet());

    for (String label : labels) {
        header.add(label + " P");
        row.add(String.format(Locale.ENGLISH, f, precisionForLabels.get(label)));

        header.add(label + " R");
        row.add(String.format(Locale.ENGLISH, f, recallForLabels.get(label)));

        header.add(label + " F1");
        row.add(String.format(Locale.ENGLISH, f, fMForLabels.get(label)));
    }

    return StringUtils.join(header, GLUE) + "\n" + StringUtils.join(row, GLUE);
}

From source file:org.focusns.common.validation.ValidationHelper.java

/**
 * ??/*w  ww  . j a  v  a2  s .  c om*/
 * 
 * @param constraintDescriptor
 * @return
 */
private static List<String> getConstraintParams(ConstraintDescriptor<?> constraintDescriptor) {
    Annotation constraintInstance = constraintDescriptor.getAnnotation();
    Class<?> constraintClass = constraintDescriptor.getAnnotation().annotationType();
    //
    List<String> params = new ArrayList<String>();
    //
    Method valueMethod = ClassUtils.getMethodIfAvailable(constraintClass, "value", (Class<?>[]) null);
    if (valueMethod != null) {
        String value = String.valueOf(ReflectionUtils.invokeMethod(valueMethod, constraintInstance));
        params.add("value:" + value);
    }
    Map<String, Object> annotationAttrs = AnnotationUtils.getAnnotationAttributes(constraintInstance);
    for (String key : annotationAttrs.keySet()) {
        if ("message".equals(key) || "payload".equals(key)) {
            continue;
        }
        //
        String value = "";
        if ("groups".equals(key)) {
            List<String> groupNames = new ArrayList<String>();
            Class[] groupClasses = (Class[]) annotationAttrs.get(key);
            for (Class groupClass : groupClasses) {
                groupNames.add(groupClass.getName());
            }
            value = StringUtils.collectionToDelimitedString(groupNames, "|");
        } else {
            value = String.valueOf(annotationAttrs.get(key));
        }
        //
        if (StringUtils.hasText(value)) {
            params.add(key + ":" + "'" + value + "'");
        }
    }
    //
    return params;
}

From source file:jvmoptions.OptionAnalyzer.java

static Map<String, Map<String, String>> readJson(Path json) throws IOException {
    ObjectMapper om = new ObjectMapper();
    TypeReference<Map<String, Map<String, String>>> ref = new TypeReference<Map<String, Map<String, String>>>() {
    };//w  w w . j a  va 2 s.  c  o  m

    Map<String, Map<String, String>> map = om.readValue(json.toFile(), ref);
    System.out.printf("%s contains %d options%n", json, map.keySet().size());
    return map;
}

From source file:com.vk.sdk.api.httpClient.VKHttpClient.java

/**
 * Prepares new "normal" request from VKRequest
 *
 * @param vkRequest Request, created for some method
 * @return Prepared request for creating VKHttpOperation
 *///from  www  .j  a v  a  2s.c o  m
public static HttpUriRequest requestWithVkRequest(VKRequest vkRequest) {
    HttpUriRequest request = null;
    VKParameters preparedParameters = vkRequest.getPreparedParameters();
    StringBuilder urlStringBuilder = new StringBuilder(String.format(Locale.US, "http%s://api.vk.com/method/%s",
            vkRequest.secure ? "s" : "", vkRequest.methodName));
    switch (vkRequest.httpMethod) {
    case GET:
        if (preparedParameters.size() > 0) {
            urlStringBuilder.append("?").append(VKStringJoiner.joinUriParams(preparedParameters));
        }
        request = new HttpGet(urlStringBuilder.toString());
        break;

    case POST:
        HttpPost post = new HttpPost(urlStringBuilder.toString());
        ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>(preparedParameters.size());
        for (Map.Entry<String, Object> entry : preparedParameters.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof VKAttachments) {
                pairs.add(
                        new BasicNameValuePair(entry.getKey(), ((VKAttachments) value).toAttachmentsString()));
            } else if (value instanceof Collection) {
                Collection<?> values = (Collection<?>) value;
                for (Object v : values) {
                    // This will add a parameter for each value in the Collection/List
                    pairs.add(new BasicNameValuePair(String.format("%s[]", entry.getKey()),
                            v == null ? null : String.valueOf(v)));
                }
            } else {
                pairs.add(new BasicNameValuePair(entry.getKey(), value == null ? null : String.valueOf(value)));
            }
        }
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
            post.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
        request = post;
        break;
    }
    Map<String, String> defaultHeaders = getDefaultHeaders();
    for (String key : defaultHeaders.keySet()) {
        request.addHeader(key, defaultHeaders.get(key));
    }

    return request;
}

From source file:com.mmj.app.common.cookie.parser.CookieUtils.java

/**
 * Map?/*from  w  w  w . j  a va  2  s  . c  om*/
 * 
 * @return KV(nullempty),null
 */
public static String mapToStr(Map<CookieKeyEnum, String> kv) {
    if (kv == null || kv.isEmpty()) {
        return null;
    }

    StringBuilder sb = new StringBuilder();
    List<CookieKeyEnum> keys = new ArrayList<CookieKeyEnum>(kv.keySet());
    for (int i = 0, j = keys.size(); i < j; i++) {
        CookieKeyEnum key = keys.get(i);
        String value = kv.get(key);
        sb.append(key.getKey()).append(COOKIE_KEY_VALUE_SEPARATOR_CHAR).append(value);
        // ??
        boolean notTheLast = (i < keys.size() - 1);
        if (notTheLast) {
            sb.append(COOKIE_MAP_SEPARATOR_CHAR);
        }
    }
    return sb.toString();
}

From source file:Main.java

/**
 * Copies the given {@link Map} containing another {@link Map} into a new
 * {@link Map}.//from  www  . j  a  v  a2 s.co  m
 * 
 * @param <A>
 *            the type of the keys of the outer map
 * @param <B>
 *            the type of the keys of the map, that is the value of the
 *            outer map
 * @param <C>
 *            the type of the values of the map, that is the value of the
 *            outer map
 * @param data
 *            the given map
 * @return If the given map was empty, a {@link Collections#emptyMap()} is
 *         returned<br>
 *         If the given map contained only one entry, a
 *         {@link Collections#singletonMap(Object, Object)}, containing
 *         said entry, is returned <br>
 *         If the given map contained more than one element, a
 *         {@link Collections#unmodifiableMap(Map)}, containing the entries
 *         of the given map, is returned.
 */
public static <A, B, C> Map<A, Map<B, C>> copyDeep(Map<A, Map<B, C>> data) {
    final int size = data.size();

    switch (size) {
    case 0:
        return Collections.emptyMap();
    case 1:
        final A key = data.keySet().iterator().next();
        return Collections.singletonMap(key, copy(data.get(key)));
    default:
        final Map<A, Map<B, C>> newData = new HashMap<A, Map<B, C>>();
        for (Map.Entry<A, Map<B, C>> entry : data.entrySet()) {
            newData.put(entry.getKey(), copy(entry.getValue()));
        }
        return Collections.unmodifiableMap(newData);
    }
}

From source file:tv.icntv.log.crawl2.commons.HttpClientUtil.java

public static String getContentPost(String url, Map<String, String> params) throws IOException {
    HttpPost httpPost = new HttpPost(url);
    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    if (params != null) {
        Set set = params.keySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Object key = iterator.next();
            Object value = params.get(key);
            formParams.add(new BasicNameValuePair(key.toString(), value.toString()));
        }/*w  w w . ja  va2s  .com*/
    }
    httpPost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"));
    httpPost.setEntity(new UrlEncodedFormEntity(formParams, HTTP.UTF_8));

    // execute
    CloseableHttpClient client = HttpClientHolder.getClient();
    return EntityUtils.toString(client.execute(httpPost).getEntity(), "utf-8");
}

From source file:me.timothy.ddd.DDDUtils.java

public static void writeJSONPretty(Writer out, Map<?, ?> map, int indentation) throws IOException {
    out.write('{');
    indentation++;//from  ww w . j av  a 2  s  .c  o  m
    boolean first = true;
    Set<?> keys = map.keySet();
    for (Object o : keys) {
        if (!(o instanceof String)) {
            throw new IllegalArgumentException("Invalid key: " + o.getClass().getName());
        }

        String str = (String) o;
        if (!first) {
            out.write(',');
        } else {
            first = false;
        }
        out.write('\n');
        writeIndentation(out, indentation);
        write(out, str, indentation);
        out.write(": ");
        Object val = map.get(o);
        write(out, val, indentation);
    }
    indentation--;
    out.write('\n');
    writeIndentation(out, indentation);
    out.write('}');
}

From source file:net.big_oh.common.web.WebUtil.java

/**
 * Calculate an <b>approximation</b> of the memory consumed by all objects
 * stored in the {@link HttpSession}. The estimate will often be greater
 * than the actual value because of "double counting" objects that appear in
 * the object graphs of multiple session attributes.
 * /*from  ww  w.ja  v  a  2  s  .c o m*/
 * @param session
 *            An HttpSession object from any web application.
 * @return An <b>approximation</b> of the memory consumed by objects stored
 *         in the HttpSession object.
 */
public static long approximateSessionSizeInBytes(HttpSession session) {
    // Strategy used here is to sum memory consumed by all key/value pairs
    // stored in the session

    long sizeInBytes = 0;

    Map<String, Integer> attributeNameMap = getSessionAttributeNameToApproxSizeInBytesMap(session);
    for (String attributeName : attributeNameMap.keySet()) {
        sizeInBytes += attributeNameMap.get(attributeName);
    }

    // Map<String, Integer> attributeMap =
    // getSessionAttributeNameToApproxSizeInBytesMap(session);
    for (String attributeName : attributeNameMap.keySet()) {
        try {
            sizeInBytes += approximateObjectSize(session.getAttribute(attributeName));
        } catch (IOException ioe) {
            logger.error("Failed to approximate size of value associated with session attribute name: "
                    + attributeName.getClass().getName(), ioe);
        }
    }

    return sizeInBytes;

}