Example usage for java.util HashMap keySet

List of usage examples for java.util HashMap keySet

Introduction

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

Prototype

public Set<K> keySet() 

Source Link

Document

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

Usage

From source file:com.example.common.ApiRequestFactory.java

/**
 * Generate the API JSON request body /*from ww  w.  ja va 2 s  .  c om*/
 */
@SuppressWarnings("unchecked")
private static String generateJsonRequestBody(Object params) {

    if (params == null) {
        return "";
    }

    HashMap<String, Object> requestParams;
    if (params instanceof HashMap) {
        requestParams = (HashMap<String, Object>) params;
    } else {
        return "";
    }

    // add parameter node
    final Iterator<String> keySet = requestParams.keySet().iterator();
    JSONObject jsonObject = new JSONObject();
    try {
        while (keySet.hasNext()) {
            final String key = keySet.next();
            jsonObject.put(key, requestParams.get(key));
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return "";
    }
    return jsonObject.toString();
}

From source file:com.jabyftw.lobstercraft.util.InventoryHolder.java

/**
 * This method will mix all items in one Map(ItemStack, amount of items)
 *
 * @param itemStacks ItemStack array/*from  w w w . ja va2s  .com*/
 * @return a map with all ItemStacks together
 */
public static HashMap<ItemStack, Integer> mergeItems(@NotNull final ItemStack[] itemStacks) {
    HashMap<ItemStack, Integer> items = new HashMap<>();

    for (ItemStack currentItem : itemStacks) {
        ItemStack similarItem = null;
        // Iterate through inserted items
        for (ItemStack insertedItem : items.keySet())
            // If currentItem is similar to a inserted item, merge them
            // Note: this doesn't consider amount, so we're safe!
            if (insertedItem.isSimilar(currentItem)) {
                similarItem = insertedItem;
                break;
            }

        if (similarItem != null)
            items.put(similarItem, items.get(similarItem) + currentItem.getAmount());
        else
            items.put(currentItem, currentItem.getAmount());
    }

    return items;
}

From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java

/**
 * Checks if is reachable.//  w w w.j  av  a  2s.  c o  m
 *
 * @param uri the uri
 * @param headers the headers
 * @return true, if is reachable
 */
public static boolean isReachable(String uri, HashMap<String, String> headers) {
    try {
        HttpURLConnection.setFollowRedirects(false);
        // note : you may also need
        // HttpURLConnection.setInstanceFollowRedirects(false)
        HttpURLConnection myURLConnection = (HttpURLConnection) new URL(uri).openConnection();
        myURLConnection.setRequestMethod("HEAD");
        for (String key : headers.keySet()) {
            myURLConnection.setRequestProperty("Authorization", headers.get(key));
        }
        LOGGER.info(myURLConnection.getResponseCode() + " / " + myURLConnection.toString());
        return (myURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:edu.ucsb.nceas.metacat.util.RequestUtil.java

/**
 * Post a request and return the response body
 * //  ww  w  . j a v  a2s  .  co m
 * @param httpClient
 *            The HttpClient to use in the post.  This is passed in because
  *            the same client may be used in several posts
 * @param url
 *            the url to post to
 * @param paramMap
 *            map of parameters to add to the post
 * @returns a string holding the response body
 */
public static String post(HttpClient httpClient, String url, HashMap<String, String> paramMap)
        throws IOException, HttpException {

    PostMethod method = new PostMethod(url);

    // Configure the form parameters
    if (paramMap != null) {
        Set<String> paramNames = paramMap.keySet();
        for (String paramName : paramNames) {
            method.addParameter(paramName, paramMap.get(paramName));
        }
    }

    // Execute the POST method
    int statusCode = httpClient.executeMethod(method);
    if (statusCode != -1) {
        String contents = method.getResponseBodyAsString();
        method.releaseConnection();
        return (contents);
    }

    return null;
}

From source file:afest.math.MyMath.java

/**
 * Return the object that has majority (# of occurrences) in the collection. T must implement equals.  
 * @param <T> Type of object to get the majority.
 * @param collection collection to extract the object that is majoritary from.
 * @return the object that occurs the most often in the collection.
 *///from w  w w .j  a  v  a2  s. co m
public static <T> T majority(Collection<T> collection) {
    HashMap<T, Integer> counts = new HashMap<T, Integer>();
    for (T aT : collection) {
        Integer count = counts.get(aT);
        if (count == null) {
            counts.put(aT, 0);
            count = counts.get(aT);
        }
        counts.put(aT, count + 1);
    }
    T majority = null;
    int maxCount = -1;
    for (T aT : counts.keySet()) {
        if (majority == null) {
            majority = aT;
            maxCount = counts.get(aT);
        }

        int count = counts.get(aT);
        if (maxCount < count) {
            majority = aT;
            maxCount = count;
        }
    }
    return majority;
}

From source file:Main.java

/**
 * Given an un-encoded URI query string, this will return a normalized, properly encoded URI query string.
 * <b>Important:</b> This method uses java's URLEncoder, which returns things that are 
 * application/x-www-form-urlencoded, instead of things that are properly octet-esacped as the URI spec
 * requires.  As a result, some substitutions are made to properly translate space characters to meet the
 * URI spec./*from   ww w.ja  v a  2 s.c o m*/
 * @param queryString
 * @return
 */
private static String normalizeQueryString(String queryString) throws UnsupportedEncodingException {
    if ("".equals(queryString) || queryString == null)
        return queryString;

    String[] pieces = queryString.split("&");
    HashMap<String, String> kvp = new HashMap<String, String>();
    StringBuffer builder = new StringBuffer("");

    for (int x = 0; x < pieces.length; x++) {
        String[] bs = pieces[x].split("=", 2);
        bs[0] = URLEncoder.encode(bs[0], "UTF-8");
        if (bs.length == 1)
            kvp.put(bs[0], null);
        else {
            kvp.put(bs[0], URLEncoder.encode(bs[1], "UTF-8").replaceAll("\\+", "%20"));
        }
    }

    // Sort the keys alphabetically, ignoring case.
    ArrayList<String> keys = new ArrayList<String>(kvp.keySet());
    Collections.sort(keys, new Comparator<String>() {
        public int compare(String o1, String o2) {
            return o1.compareToIgnoreCase(o2);
        }
    });

    // With the alphabetic list of parameter names, re-build the query string.
    for (int x = 0; x < keys.size(); x++) {
        // Some parameters have no value, and are simply present.  If so, we put null in kvp,
        // and we just put the parameter name, no "=value".
        if (kvp.get(keys.get(x)) == null)
            builder.append(keys.get(x));
        else
            builder.append(keys.get(x) + "=" + kvp.get(keys.get(x)));

        if (x < (keys.size() - 1))
            builder.append("&");
    }

    return builder.toString();
}

From source file:de.adesso.referencer.search.helper.ElasticConfig.java

public static String buildSearchQuery(HashMap<String, String> fieldvalue) {
    String result = null;//from w  w  w  .  j a  va  2s .co  m
    if (fieldvalue == null)
        return null;
    if (fieldvalue.size() <= 0)
        return null;
    result = "{\"query\": { \"bool\": {\"must\": [";
    String matchString = null;
    for (String s : fieldvalue.keySet()) {
        matchString = buildMatchString(s, fieldvalue.get(s));
        if (matchString != null)
            result += "\n" + matchString + ",";
    }
    result = result.substring(0, result.length() - 1) + "\n";
    result += "]}}}";
    return result;
}

From source file:LineageSimulator.java

/**
 * Sample from a binomial with mean = true freq(f) and variance f(1-f)/coverage + sequencing noise 
 *//* w ww .  j a va  2 s. co  m*/
public static HashMap<Mutation.SNV, double[]> addNoise(HashMap<Mutation.SNV, double[]> multiSampleFrequencies,
        int coverage, int numSamples) {
    HashMap<Mutation.SNV, double[]> noisyMultiSampleFrequencies = new HashMap<Mutation.SNV, double[]>();
    for (Mutation.SNV snv : multiSampleFrequencies.keySet()) {
        noisyMultiSampleFrequencies.put(snv, new double[numSamples]);
        for (int i = 1; i < numSamples; i++) {
            int nReadsSNV = 0;
            if (multiSampleFrequencies.get(snv)[i] > 0) {
                BinomialGenerator b1 = new BinomialGenerator(coverage, multiSampleFrequencies.get(snv)[i],
                        new Random());
                nReadsSNV = b1.nextValue();
            }
            int nReadsRef = coverage - nReadsSNV;
            // add sequencing noise
            int nSNV = 0;
            if (nReadsSNV > 0) {
                BinomialGenerator snvR = new BinomialGenerator(nReadsSNV, 1 - Parameters.SEQUENCING_ERROR,
                        new Random());
                nSNV += snvR.nextValue();
            }
            BinomialGenerator flipR = new BinomialGenerator(nReadsRef,
                    ((double) 1 / 3) * Parameters.SEQUENCING_ERROR, new Random());
            nSNV += flipR.nextValue();
            noisyMultiSampleFrequencies.get(snv)[i] = (double) nSNV / coverage;
        }
    }
    return noisyMultiSampleFrequencies;
}

From source file:net.sf.maltcms.chromaui.project.spi.DBProjectFactory.java

private static void addNormalizationDescriptors(Map<String, Object> props, Map<File, File> importFileMap,
        LinkedHashMap<File, IChromatogramDescriptor> fileToDescriptor) {
    HashMap<File, INormalizationDescriptor> normalizationDescriptors = (HashMap<File, INormalizationDescriptor>) props
            .get(DBProjectVisualPanel3.PROP_FILE_TO_NORMALIZATION);
    for (File file : normalizationDescriptors.keySet()) {
        fileToDescriptor.get(importFileMap.get(file))
                .setNormalizationDescriptor(normalizationDescriptors.get(file));
    }//from   w  w  w.  ja  v  a 2  s  . c  o  m
}

From source file:org.ofbiz.party.tool.SmsSimpleClient.java

/**
 * ??http POSThttp?/*from   w w  w . j  ava2s.co m*/
 * 
 * @param urlstr url
 * @return
 */
public static String doPostRequest(String urlstr, HashMap<String, String> content) {
    HttpClient client = new DefaultHttpClient();
    client.getParams().setIntParameter("http.socket.timeout", 10000);
    client.getParams().setIntParameter("http.connection.timeout", 5000);
    List<NameValuePair> ls = new ArrayList<NameValuePair>();
    for (String key : content.keySet()) {
        NameValuePair param = new BasicNameValuePair(key, content.get(key));
        ls.add(param);
    }
    HttpEntity entity = null;
    String entityContent = null;
    try {
        HttpPost httpPost = new HttpPost(urlstr.toString());
        UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(ls, "UTF-8");
        httpPost.setEntity(uefe);

        HttpResponse httpResponse = client.execute(httpPost);
        entityContent = EntityUtils.toString(httpResponse.getEntity());

    } catch (Exception e) {
        Debug.logError(e, module);
    } finally {
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (Exception e) {
                Debug.logError(e, module);
            }
        }
    }
    return entityContent;
}