Example usage for java.util HashMap entrySet

List of usage examples for java.util HashMap entrySet

Introduction

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

Prototype

Set entrySet

To view the source code for java.util HashMap entrySet.

Click Source Link

Document

Holds cached entrySet().

Usage

From source file:br.unicamp.cst.learning.QLearning.java

/**
* Selects the best action for this state with probability "e", 
* and a random one with probability (1-e) 
*  If a given state has no record of one or more actions, it will consider them as valued 0.
* @param state//from   w  w  w  . ja v a  2  s. c  o m
* @param e
 * @return selectedAction
*/
public String getAction(String state) {//TODO should improve this. It should consider all non explored actions as being equally 0 for all purposes
    //      System.out.println("Inside get action");
    String selectedAction = null;
    if (r.nextDouble() <= e) { //TODO Use boltzmann distribution here?
        //         if(ql.getAction(stringState)!=null){
        //            action=ql.getAction(stringState);//
        //-----

        if (this.Q.get(state) != null) {
            ArrayList<String> actionsLeft = new ArrayList<String>();
            actionsLeft.addAll(this.actionsList);
            HashMap<String, Double> actionsQ = this.Q.get(state);
            double bestQval = -Double.POSITIVE_INFINITY;
            Iterator<Entry<String, Double>> it = actionsQ.entrySet().iterator();

            while (it.hasNext()) {
                Entry<String, Double> pairs = it.next();
                double qVal = pairs.getValue();
                String qAct = pairs.getKey();
                if (qVal > bestQval) {
                    bestQval = qVal;
                    selectedAction = qAct;
                }
                actionsLeft.remove(qAct);
            }
            if ((bestQval < 0) && (actionsLeft.size() > 0)) {
                //this means we should randomly choose from the other actions;
                selectedAction = selectRandomAction(actionsLeft);
            }
            if (showDebugMessages) {
                System.out.println("Selected the best available action.");
            }
        } else {
            //            System.out.println("Inside else null");
            //               selectedAction=null;
            selectedAction = selectRandomAction(actionsList);
            if (showDebugMessages) {
                System.out.println("Selected a random action because there was no available suggestion.");
            }
        }

        //         }else{
        //            action=selectRandomAction();
        //         }
    } else {
        if (showDebugMessages) {
            System.out.println("Naturally selected a random action.");
        }
        selectedAction = selectRandomAction(actionsList);
    }
    return selectedAction;
}

From source file:com.bmc.gibraltar.automation.dataprovider.RestDataProvider.java

public String startProcessWithInputs(String processDefinitionId, HashMap<String, String> inputs) {
    JsonObject request = buildRequestToStartProcessInstance(processDefinitionId);
    JsonObject inputsOfProcessDefinition = new JsonObject();
    for (Map.Entry<String, String> entry : inputs.entrySet()) {
        inputsOfProcessDefinition.addProperty(entry.getKey(), entry.getValue());
    }/*from  www.ja  v  a  2 s .co  m*/
    request.add("processInputValues", inputsOfProcessDefinition);
    String bodyOfRequest = new GsonBuilder().create().toJson(request);
    return processApi.startProcessInstance(bodyOfRequest).extract().toString();
}

From source file:it.polito.tellmefirst.web.rest.clients.ClientEpub.java

private void removeEmptyItems(HashMap lhm) {

    LOG.debug("[removeEmptyItems] - BEGIN");

    Set set = lhm.entrySet();
    Iterator i = set.iterator();//from   w  w  w  .  j  a va2  s  .c o  m
    Pattern pattern = Pattern.compile("([a-zA-Z0-9]{1,}\\s){15,}"); //check if at least 15 words

    while (i.hasNext()) {
        Map.Entry me = (Map.Entry) i.next();
        Matcher matcher = pattern.matcher(me.getValue().toString());
        if (!matcher.find()) {
            LOG.info("Remove empty item: " + me.getKey().toString());
            i.remove();
        }
    }

    LOG.debug("[removeEmptyItems] - END");
}

From source file:com.google.gwt.emultest.java.util.IdentityHashMapTest.java

public void testEntrySetEntrySetterNull() {
    HashMap hashMap = new HashMap();
    hashMap.put(null, 2);/*from   w w w .j  a va2 s  . co  m*/
    Set entrySet = hashMap.entrySet();
    Entry entry = (Entry) entrySet.iterator().next();

    entry.setValue(3);
    assertEquals(3, hashMap.get(null));

    hashMap.put(null, 4);
    assertEquals(4, entry.getValue());

    assertEquals(1, hashMap.size());
}

From source file:GitBackend.GitAPI.java

private void printMap(HashMap<String, DateTime> commitMap) {
    Iterator it = commitMap.entrySet().iterator();

    Map.Entry<String, DateTime> mostRecentCommit = null;
    System.out.println("Number of commits: " + commitMap.size());
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        System.out.println(pair.getKey() + " --- " + pair.getValue());

    }/*from w ww . ja v a 2 s.com*/
}

From source file:com.Upwork.api.OAuthClient.java

/**
 * Send signed GET OAuth request/*from  ww  w  .  jav a2s .  co m*/
 * 
 * @param   url Relative URL
 * @param   type Type of HTTP request (HTTP method)
 * @param   params Hash of parameters
 * @throws   JSONException If JSON object is invalid or request was abnormal
 * @return   {@link JSONObject} JSON Object that contains data from response
 * */
private JSONObject sendGetRequest(String url, Integer type, HashMap<String, String> params)
        throws JSONException {
    String fullUrl = getFullUrl(url);
    HttpGet request = new HttpGet(fullUrl);

    if (params != null) {
        URI uri;
        String query = "";
        try {
            URIBuilder uriBuilder = new URIBuilder(request.getURI());

            // encode values and add them to the request
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                // to prevent double encoding, we need to create query string ourself
                // uriBuilder.addParameter(key, URLEncoder.encode(value).replace("%3B", ";"));
                query = query + key + "=" + value.replace("&", "&amp;") + "&";
                // what the hell is going on in java - no adequate way to encode query string
                // lets temporary replace "&" in the value, to encode it manually later
            }
            // this routine will encode query string
            uriBuilder.setCustomQuery(query);
            uri = uriBuilder.build();

            // re-create request to have validly encoded ampersand
            request = new HttpGet(fullUrl + "?" + uri.getRawQuery().replace("&amp;", "%26"));
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        mOAuthConsumer.sign(request);
    } catch (OAuthException e) {
        e.printStackTrace();
    }

    return UpworkRestClient.getJSONObject(request, type);
}

From source file:ws.wamp.jawampa.client.SessionEstablishedState.java

void clearAllSubscriptions(Throwable e) {
    for (HashMap<String, SubscriptionMapEntry> subscriptionByUri : subscriptionsByFlags.values()) {
        for (Entry<String, SubscriptionMapEntry> entry : subscriptionByUri.entrySet()) {
            for (Subscriber<? super PubSubData> s : entry.getValue().subscribers) {
                if (e == null)
                    s.onCompleted();/*from  w  w  w . j av  a 2s  .co m*/
                else
                    s.onError(e);
            }
            entry.getValue().state = PubSubState.Unsubscribed;
        }
        subscriptionByUri.clear();
    }
    subscriptionsBySubscriptionId.clear();
}

From source file:org.lansir.beautifulgirls.proxy.ProxyInvocationHandler.java

/** 
 * Dynamic proxy invoke// w w w  .  j a  v a2 s .c  o m
 */
public Object invoke(Object proxy, Method method, Object[] args)
        throws AkInvokeException, AkServerStatusException, AkException, Exception {
    AkPOST akPost = method.getAnnotation(AkPOST.class);
    AkGET akGet = method.getAnnotation(AkGET.class);

    AkAPI akApi = method.getAnnotation(AkAPI.class);
    Annotation[][] annosArr = method.getParameterAnnotations();
    String invokeUrl = akApi.url();
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

    // AkApiParams to hashmap, filter out of null-value
    HashMap<String, File> filesToSend = new HashMap<String, File>();
    HashMap<String, String> paramsMapOri = new HashMap<String, String>();
    HashMap<String, String> paramsMap = getRawApiParams2HashMap(annosArr, args, filesToSend, paramsMapOri);
    // Record this invocation
    ApiInvokeInfo apiInvokeInfo = new ApiInvokeInfo();
    apiInvokeInfo.apiName = method.getName();
    apiInvokeInfo.paramsMap.putAll(paramsMap);
    apiInvokeInfo.url = invokeUrl;
    // parse '{}'s in url
    invokeUrl = parseUrlbyParams(invokeUrl, paramsMap);
    // cleared hashmap to params, and filter out of the null value
    Iterator<Entry<String, String>> iter = paramsMap.entrySet().iterator();
    while (iter.hasNext()) {
        Entry<String, String> entry = iter.next();
        params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }

    // get the signature string if using
    AkSignature akSig = method.getAnnotation(AkSignature.class);
    if (akSig != null) {
        Class<?> clazzSignature = akSig.using();
        if (clazzSignature.getInterfaces().length > 0 // TODO: NEED VERIFY WHEN I HAVE TIME
                && InvokeSignature.class.getName().equals(clazzSignature.getInterfaces()[0].getName())) {
            InvokeSignature is = (InvokeSignature) clazzSignature.getConstructors()[0].newInstance();
            String sigValue = is.signature(akSig, invokeUrl, params, paramsMapOri);
            String sigParamName = is.getSignatureParamName();
            if (sigValue != null && sigParamName != null && sigValue.length() > 0
                    && sigParamName.length() > 0) {
                params.add(new BasicNameValuePair(sigParamName, sigValue));
            }
        }
    }

    // choose POST GET PUT DELETE to use for this invoke
    String retString = "";
    if (akGet != null) {
        StringBuilder sbUrl = new StringBuilder(invokeUrl);
        if (!(invokeUrl.endsWith("?") || invokeUrl.endsWith("&"))) {
            sbUrl.append("?");
        }
        for (NameValuePair nvp : params) {
            sbUrl.append(nvp.getName());
            sbUrl.append("=");
            sbUrl.append(nvp.getValue());
            sbUrl.append("&");
        } // now default using UTF-8, maybe improved later
        retString = HttpInvoker.get(sbUrl.toString());
    } else if (akPost != null) {
        if (filesToSend.isEmpty()) {
            retString = HttpInvoker.post(invokeUrl, params);
        } else {
            retString = HttpInvoker.postWithFilesUsingURLConnection(invokeUrl, params, filesToSend);
        }
    } else { // use POST for default
        retString = HttpInvoker.post(invokeUrl, params);
    }

    // invoked, then add to history
    //ApiStats.addApiInvocation(apiInvokeInfo);

    //Log.d(TAG, retString);

    // parse the return-string
    Class<?> returnType = method.getReturnType();
    try {
        if (String.class.equals(returnType)) { // the result return raw string
            return retString;
        } else { // return object using json decode
            return JsonMapper.json2pojo(retString, returnType);
        }
    } catch (IOException e) {
        throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, e.getMessage(), e);
    }
    /*
     * also can use gson like this eg. 
     *  Gson gson = new Gson();
     *  return gson.fromJson(HttpInvoker.post(url, params), returnType);
     */
}

From source file:org.akita.proxy.ProxyInvocationHandler.java

/** 
 * Dynamic proxy invoke/*  w ww  .  jav a 2 s . c  o m*/
 */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    AkPOST akPost = method.getAnnotation(AkPOST.class);
    AkGET akGet = method.getAnnotation(AkGET.class);

    AkAPI akApi = method.getAnnotation(AkAPI.class);
    Annotation[][] annosArr = method.getParameterAnnotations();
    String invokeUrl = akApi.url();
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

    // AkApiParams to hashmap, filter out of null-value
    HashMap<String, File> filesToSend = new HashMap<String, File>();
    HashMap<String, String> paramsMapOri = new HashMap<String, String>();
    HashMap<String, String> paramsMap = getRawApiParams2HashMap(annosArr, args, filesToSend, paramsMapOri);
    // Record this invocation
    ApiInvokeInfo apiInvokeInfo = new ApiInvokeInfo();
    apiInvokeInfo.apiName = method.getName();
    apiInvokeInfo.paramsMap.putAll(paramsMapOri);
    apiInvokeInfo.url = invokeUrl;
    // parse '{}'s in url
    invokeUrl = parseUrlbyParams(invokeUrl, paramsMap);
    // cleared hashmap to params, and filter out of the null value
    Iterator<Entry<String, String>> iter = paramsMap.entrySet().iterator();
    while (iter.hasNext()) {
        Entry<String, String> entry = iter.next();
        params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }

    // get the signature string if using
    AkSignature akSig = method.getAnnotation(AkSignature.class);
    if (akSig != null) {
        Class<?> clazzSignature = akSig.using();
        if (clazzSignature.getInterfaces().length > 0 // TODO: NEED VERIFY WHEN I HAVE TIME
                && InvokeSignature.class.getName().equals(clazzSignature.getInterfaces()[0].getName())) {
            InvokeSignature is = (InvokeSignature) clazzSignature.getConstructors()[0].newInstance();
            String sigValue = is.signature(akSig, invokeUrl, params, paramsMapOri);
            String sigParamName = is.getSignatureParamName();
            if (sigValue != null && sigParamName != null && sigValue.length() > 0
                    && sigParamName.length() > 0) {
                params.add(new BasicNameValuePair(sigParamName, sigValue));
            }
        }
    }

    // choose POST GET PUT DELETE to use for this invoke
    String retString = "";
    if (akGet != null) {
        StringBuilder sbUrl = new StringBuilder(invokeUrl);
        if (!(invokeUrl.endsWith("?") || invokeUrl.endsWith("&"))) {
            sbUrl.append("?");
        }
        for (NameValuePair nvp : params) {
            sbUrl.append(nvp.getName());
            sbUrl.append("=");
            sbUrl.append(nvp.getValue());
            sbUrl.append("&");
        } // now default using UTF-8, maybe improved later
        retString = HttpInvoker.get(sbUrl.toString());
    } else if (akPost != null) {
        if (filesToSend.isEmpty()) {
            retString = HttpInvoker.post(invokeUrl, params);
        } else {
            retString = HttpInvoker.postWithFilesUsingURLConnection(invokeUrl, params, filesToSend);
        }
    } else { // use POST for default
        retString = HttpInvoker.post(invokeUrl, params);
    }

    // invoked, then add to history
    //ApiStats.addApiInvocation(apiInvokeInfo);

    //Log.d(TAG, retString);

    // parse the return-string
    final Class<?> returnType = method.getReturnType();
    try {
        if (String.class.equals(returnType)) { // the result return raw string
            return retString;
        } else { // return object using json decode
            return JsonMapper.json2pojo(retString, returnType);
        }
    } catch (Exception e) {
        Log.e(TAG, retString, e); // log can print the error return-string
        throw new AkInvokeException(AkInvokeException.CODE_JSONPROCESS_EXCEPTION, e.getMessage(), e);
    }
}

From source file:com.dao.ShopThread.java

private void initCookies(LoginSys login) {
    HashMap<String, String> cookieMap = login.getCookies();
    this.cookies = new HashMap<String, String>();
    for (Map.Entry<String, String> entry : cookieMap.entrySet()) {
        this.cookies.put(entry.getKey(), entry.getValue());
    }/*from w w  w.ja  v a2s.  c  o  m*/
}