Example usage for java.util HashMap size

List of usage examples for java.util HashMap size

Introduction

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

Prototype

int size

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

Click Source Link

Document

The number of key-value mappings contained in this map.

Usage

From source file:edu.utexas.cs.tactex.BrokerUtilsTest.java

@Test
public void test_initializedPredictedFromCurrentPredictions() {
    HashMap<CustomerInfo, HashMap<TariffSpecification, Integer>> oldmap = new HashMap<CustomerInfo, HashMap<TariffSpecification, Integer>>();

    HashMap<CustomerInfo, HashMap<TariffSpecification, Double>> newmap = BrokerUtils
            .initializePredictedFromCurrentSubscriptions(oldmap);

    // empty map//from   w  ww  .  j a  v a2  s .  c om
    assertEquals("empty subscriptions", 0, newmap.size());

    // 1 customer, no subscriptions
    CustomerInfo cust1 = new CustomerInfo("cust1", 10);
    oldmap.put(cust1, new HashMap<TariffSpecification, Integer>());
    newmap = BrokerUtils.initializePredictedFromCurrentSubscriptions(oldmap);
    assertEquals("1 customer, no subscriptions, map size", 1, newmap.size());
    assertEquals("1 customer, no subscriptions, subscriptions size", 0, newmap.get(cust1).size());

    Broker thebroker = new Broker("testBroker");
    // 1 customer, 1 tariff subscriptions
    TariffSpecification tariff1 = new TariffSpecification(thebroker, PowerType.CONSUMPTION);
    oldmap.get(cust1).put(tariff1, 5);
    newmap = BrokerUtils.initializePredictedFromCurrentSubscriptions(oldmap);
    assertEquals("1 customer, 1 subscription, map size", 1, newmap.size());
    assertEquals("1 customer, 1 subscription, subscriptions size", 1, newmap.get(cust1).size());
    assertEquals("1 customer, 1 subscription, num subs", 5.0, newmap.get(cust1).get(tariff1), 1e-6);

    // 1 customer, 2 tariff subscriptions
    TariffSpecification tariff2 = new TariffSpecification(thebroker, PowerType.CONSUMPTION);
    oldmap.get(cust1).put(tariff2, 3);
    newmap = BrokerUtils.initializePredictedFromCurrentSubscriptions(oldmap);
    assertEquals("1 customer, 2 subscription, map size", 1, newmap.size());
    assertEquals("1 customer, 2 subscription, subscriptions size", 2, newmap.get(cust1).size());
    assertEquals("1 customer, 2 subscription, num subs tariff1", 5.0, newmap.get(cust1).get(tariff1), 1e-6);
    assertEquals("1 customer, 2 subscription, num subs tariff2", 3.0, newmap.get(cust1).get(tariff2), 1e-6);

    // 2 customer, 2 tariff subscriptions
    CustomerInfo cust2 = new CustomerInfo("cust2", 20);
    oldmap.put(cust2, new HashMap<TariffSpecification, Integer>());
    oldmap.get(cust2).put(tariff1, 15);
    oldmap.get(cust2).put(tariff2, 5);
    newmap = BrokerUtils.initializePredictedFromCurrentSubscriptions(oldmap);
    assertEquals("2 customer, 2 subscription, map size", 2, newmap.size());
    // missing? test in current line 
    assertEquals("2 customer, 2 subscription, cust1 subscriptions size", 2, newmap.get(cust1).size());
    assertEquals("2 customer, 2 subscription, cust1 num subs tariff1", 5.0, newmap.get(cust1).get(tariff1),
            1e-6);
    assertEquals("2 customer, 2 subscription, cust1 num subs tariff2", 3.0, newmap.get(cust1).get(tariff2),
            1e-6);
    assertEquals("2 customer, 2 subscription, cust2 subscriptions size", 2, newmap.get(cust2).size());
    assertEquals("2 customer, 2 subscription, cust2 num subs tariff1", 15.0, newmap.get(cust2).get(tariff1),
            1e-6);
    assertEquals("2 customer, 2 subscription, cust2 num subs tariff2", 5.0, newmap.get(cust2).get(tariff2),
            1e-6);
}

From source file:DAO.BestellingDAOJson.java

@Override
public void createBestelling(Bestelling bestelling) {
    //Bestelling catalogus;
    HashMap<String, Bestelling> catalogus = new HashMap<>();
    //catalogus = bestelling;
    try (FileReader read = new FileReader("C:\\Users\\maurice\\Desktop\\Workshoptest.json");) {

        catalogus = gson.fromJson(read, artikelType);
        int nieuweID = catalogus.size() + 1;
        if (bestelling.getBestelling_id() == 0) {
            bestelling.setBestelling_id(4); //(nieuweID);
        }/*from  w ww  .ja v  a  2 s.com*/
    } catch (IOException ex) {
        logger.error("create input/output " + ex);
    }
    try (FileWriter file = new FileWriter("C:\\Users\\maurice\\Desktop\\Workshoptest.json", true)) {
        catalogus.put(bestelling.getKlant_id() + "_" + bestelling.getBestelling_id(), bestelling);
        file.write(gson.toJson(catalogus, artikelType));
        logger.trace("artikel toegeveogd aan catalogus ");
    } catch (IOException ex) {
        logger.error("create input/output " + ex);
    }

}

From source file:com.antelink.sourcesquare.client.scan.ProcessWorker.java

private void analyzeMapWithCount(int times, HashMap<String, String> tempMap) throws Exception {
    try {/*from  w w w.  j  a  va2s  .c  om*/
        logger.debug("pass " + times + ": analyzing files " + tempMap.values());
        this.engine.discover(tempMap);
    } catch (Exception e) {
        logger.debug("Error while analyzing", e);
        if (times > RETRIES) {
            logger.error(RETRIES + " time retry done... giving up!");
            // do as if the result where found
            this.engine.DummyPass(e, tempMap.size());
            throw e;
        } else {
            logger.debug("retrying...");
            analyzeMapWithCount(times + 1, tempMap);
        }
    }
}

From source file:at.ac.tuwien.qse.sepm.service.impl.TagServiceImpl.java

@Override
public List<Tag> getMostFrequentTags(List<Photo> photos) throws ServiceException {
    LOGGER.debug("Entering getMostFrequentTags with {}", photos);

    HashMap<Tag, Integer> counter = new HashMap<>();

    // count the frequency of each tag
    for (Photo photo : photos) {
        for (Tag tag : photo.getData().getTags()) {
            if (counter.containsKey(tag)) {
                counter.put(tag, counter.get(tag) + 1);
            } else {
                counter.put(tag, 1);//w ww .ja  va  2s. c  o  m
            }
        }
    }

    if (counter.size() == 0) {
        throw new ServiceException("No Tags found");
    }

    // return the most frequent tags
    return counter.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).limit(5)
            .map(Map.Entry::getKey).collect(Collectors.toList());
}

From source file:biocode.fims.ezid.EzidService.java

/**
 * Serialize a HashMap of metadata name/value pairs as an ANVL String value. If the
 * HashMap is null, or if it has no entries, then return a null string.
 *
 * @param metadata the Map of metadata name/value pairs
 *
 * @return an ANVL serialize String//  ww w  .j av a 2  s  . co  m
 */
private String serializeAsANVL(HashMap<String, String> metadata) {
    StringBuffer buffer = new StringBuffer();
    if (metadata != null && metadata.size() > 0) {
        for (Map.Entry<String, String> entry : metadata.entrySet()) {
            buffer.append(escape(entry.getKey()) + ": " + escape(entry.getValue()) + "\n");
        }
    }
    String anvl = null;
    if (buffer != null) {
        anvl = buffer.toString();
    }
    return anvl;
}

From source file:com.ba.forms.bookingForm.BABookingAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();
    BABookingDTO vo = new BABookingDTO();

    try {/*from  w w  w  .j av a2 s.  c  om*/
        logger.info(" get method starts here");
        String foodId = request.getParameter("search");
        HashMap hashMpBookingDet = BABookingFactory.getInstanceOfBABookingFactory().getBookingDtls(foodId);
        json.put("exception", "");
        json.put("BookingDets", hashMpBookingDet);
        json.put("BookingExit", hashMpBookingDet.size());

        //  logger.warn("strCurrent PageNo ------------->"+objPageCount);
    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}

From source file:org.myrobotlab.service.HttpClient.java

public HttpData processResponse(HttpUriRequest request, HashMap<String, String> fields) throws IOException {
    HttpData data = new HttpData(request.getURI().toString());
    if (fields == null) {

        fields = formFields;//from   w ww. ja  v  a2s  .co  m
    }

    if (request.getClass().equals(HttpPost.class) && formFields.size() > 0) {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(fields.size());
        for (String nvPairKey : fields.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(nvPairKey, fields.get(nvPairKey)));
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }
    }
    HttpResponse response = client.execute(request);
    StatusLine statusLine = response.getStatusLine();
    data.responseCode = statusLine.getStatusCode();
    HttpEntity entity = response.getEntity();
    Header header = entity.getContentType();
    if (header != null) {
        data.contentType = header.getValue().toString();
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    response.getEntity().writeTo(baos);
    data.data = baos.toByteArray();

    // publishing
    invoke("publishHttpData", data);
    if (data.data != null) {
        invoke("publishHttpResponse", new String(data.data));
    }

    return data;
}

From source file:com.mc.printer.model.panel.task.BuildGuideTask.java

@Override
public Object doBackgrounp() {
    javax.swing.JTabbedPane tabs = AutoPrinterApp.getMainView().getMainWorkPanel();
    if (tabs != null) {
        if (tabs.getSelectedIndex() >= 0) {
            Component selectedcom = tabs.getSelectedComponent();
            if (selectedcom instanceof GuideWork) {
                GuideWork selectPanel = (GuideWork) selectedcom;
                GuideBean presentBeansForm = selectPanel.getBeansForm();

                logger.debug("selected tab:" + selectPanel.getName());
                //?
                GuideBean beansForm;/* ww  w .ja  va 2s.c  om*/
                try {
                    beansForm = presentBeansForm.clone();
                } catch (CloneNotSupportedException ex) {
                    logger.error(ex.getMessage());
                    beansForm = presentBeansForm;
                }

                String backGroundImg = beansForm.getBackgoundImg();

                //
                Set<String> imgArray = new HashSet();

                if (backGroundImg != null) {
                    File file = new File(backGroundImg);
                    if (file.exists() && file.isFile()) {
                        beansForm.setBackgoundImg(file.getName());
                        imgArray.add(backGroundImg);
                    } else {
                        beansForm.setBackgoundImg("");
                    }
                } else {
                    beansForm.setBackgoundImg("");
                }

                HashMap<String, GuideCompBean> parameterMap = new HashMap<String, GuideCompBean>();
                HashMap<String, GuideCompBean> parentParameterMap = selectPanel.getSavedForms();
                deepCloneMap(parameterMap, parentParameterMap);

                if (parameterMap.size() > 0) {
                    Set set = parameterMap.keySet();
                    //???
                    List<GuideCompBean> beans = new ArrayList();
                    Iterator it = set.iterator();
                    while (it.hasNext()) {
                        GuideCompBean com = parameterMap.get(it.next().toString());
                        beans.add(com);

                        String pressedIcon = com.getPressedIcon();
                        String icon = com.getIcon();
                        if (pressedIcon != null && !pressedIcon.equals("")) {

                            File pressfile = new File(pressedIcon);
                            if (pressfile.exists() && pressfile.isFile()) {
                                imgArray.add(pressedIcon);
                                com.setPressedIcon(pressfile.getName());
                            } else {
                                com.setPressedIcon("");
                            }

                        }
                        if (icon != null && !icon.equals("")) {
                            File iconfile = new File(icon);
                            if (iconfile.exists() && iconfile.isFile()) {
                                imgArray.add(icon);
                                com.setIcon(iconfile.getName());
                            } else {
                                com.setIcon("");
                            }
                        }
                    }
                    beansForm.setElements(beans);

                    BaseFileChoose fileChoose = new BaseFileChoose("?",
                            new String[] { Constants.MODEL_SUFFIX }, AutoPrinterApp.getMainFrame());
                    String selectedPath = fileChoose.showSaveDialog();
                    if (!selectedPath.trim().equals("")) {

                        //get formname
                        selectedPath = selectedPath + File.separator + beansForm.getGuideName();
                        //String time=DateHelper.format(new Date(), "yyyyMMddHHmmss");
                        String finalZip = selectedPath;
                        if (!selectedPath.endsWith("." + Constants.GUIDE_SUFFIX)) {
                            finalZip = selectedPath + "." + Constants.GUIDE_SUFFIX;
                        }

                        String tempDir = selectedPath + File.separator + Constants.GUIDE_TEMP_DIR;

                        String xmlPath = tempDir + File.separator + beansForm.getGuideName() + ".xml";
                        XMLHelper helper = new XMLHelper(xmlPath, beansForm);
                        try {
                            helper.write();
                        } catch (JAXBException ex) {
                            ex.printStackTrace();
                            logger.error(ex.getMessage());
                            return ex;
                        }

                        File paramFile = new File(xmlPath);
                        if (paramFile.isFile() && paramFile.exists()) {
                            try {
                                logger.info("copy file and zip temp for:" + tempDir + ",total of attached file:"
                                        + imgArray.size());
                                File _temp = new File(tempDir);
                                for (String img : imgArray) {
                                    File imgFile = new File(img);
                                    logger.debug("copy image:" + imgFile.getName());
                                    FileUtils.copyFileToDirectory(imgFile, _temp);
                                }

                                ZipHelper.createZip(tempDir, finalZip);
                                logger.info("zip file successfully.");
                                return "??.\r\n" + finalZip;
                            } catch (IOException ex) {
                                ex.printStackTrace();
                                logger.error(ex.getMessage());
                                return ex;
                            } finally {
                                try {
                                    FileUtils.deleteDirectory(new File(selectedPath));
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                                    logger.error(ex.getMessage());
                                    return ex;
                                }
                            }
                        } else {
                            logger.error("generator faild for:" + xmlPath);
                        }
                    }
                } else {
                    return "??.";
                }
            } else {
                return "??????.";
            }
        } else {
            return "?.";
        }
    } else {
        return "?.";
    }
    return null;
}

From source file:edu.ku.brc.specify.toycode.RegAdder.java

/**
 * @param mv/* www.  ja va 2s.c o m*/
 */
private void insertTrack(final HashMap<String, String> mv) {
    if (mv.size() > 0) {
        /*
        +------------------+-------------+------+-----+---------+----------------+
        | Field            | Type        | Null | Key | Default | Extra          |
        +------------------+-------------+------+-----+---------+----------------+
        | TrackID          | int(11)     | NO   | PRI | NULL    | auto_increment | 
        | TimestampCreated | datetime    | NO   |     | NULL    |                | 
        | Id               | varchar(64) | YES  |     | NULL    |                | 
        | CountAmt         | int(11)     | YES  |     | NULL    |                | 
        +------------------+-------------+------+-----+---------+----------------+
        4 rows in set (0.00 sec)
                
        mysql> describe trackitem;
        +-------------+-------------+------+-----+---------+----------------+
        | Field       | Type        | Null | Key | Default | Extra          |
        +-------------+-------------+------+-----+---------+----------------+
        | TrackItemID | int(11)     | NO   | PRI | NULL    | auto_increment | 
        | Name        | varchar(64) | NO   |     | NULL    |                | 
        | CountAmt    | int(11)     | YES  |     | NULL    |                | 
        | Value       | varchar(64) | YES  |     | NULL    |                | 
        | TrackID     | int(11)     | NO   | MUL | NULL    |                | 
        +-------------+-------------+------+-----+---------+----------------+
        */
        try {

            String id = mv.get("id");
            String ip = mv.get("IP");

            if (StringUtils.isNotEmpty(id) && (ip == null || !ip.startsWith("129.237.201"))) {
                cnt++;
                if (cnt % 100 == 0) {
                    System.out.println(cnt);
                }

                int recCnt = BasicSQLUtils
                        .getCountAsInt(String.format("SELECT COUNT(*) FROM track WHERE Id = '%s'", id));
                if (recCnt == 0) // Insert
                {

                    Timestamp timeStamp = getTimestamp(mv.get("date"));
                    if (timeStamp.getTime() < startDate)
                        return;

                    trkStmt1.setTimestamp(1, timeStamp);
                    trkStmt1.setString(2, id);
                    trkStmt1.setInt(3, 1);

                    //pStmt.toString();

                    if (trkStmt1.executeUpdate() == 1) {
                        recCnt++;
                        if (recCnt % 100 == 0) {
                            System.out.println(recCnt);
                        }

                        Integer trkId = BasicSQLUtils.getInsertedId(trkStmt1);
                        doTrackInserts(trkId, mv, trkStmt2);

                    } else {
                        throw new RuntimeException("Error insert track for ID: " + id);
                    }

                } else // Update
                {
                    recCnt = BasicSQLUtils
                            .getCountAsInt(String.format("SELECT CountAmt FROM track WHERE Id = '%s'", id)) + 1;
                    Integer trackId = BasicSQLUtils
                            .getCount(String.format("SELECT TrackID FROM track WHERE Id = '%s'", id));
                    if (trackId != null) {
                        trkStmt4.setInt(1, recCnt);
                        trkStmt4.setInt(2, trackId);

                        if (trkStmt4.executeUpdate() == 1) {
                            for (String key : mv.keySet()) {
                                String sql = String.format(
                                        "SELECT TrackItemID FROM trackitem WHERE TrackID = %d AND Name ='%s'",
                                        trackId, key);
                                Integer trackItemId = BasicSQLUtils.getCount(sql);
                                if (trackItemId == null) // Insert
                                {
                                    doTrackInserts(trackId, mv, trkStmt2);

                                } else // Update
                                {
                                    doTrackUpdate(trackItemId, mv.get(key), trkStmt3);
                                }
                            }
                        } else {
                            log.error(trkStmt4.toString());
                            log.error("Error updating " + id);
                        }
                    }
                }
            }

        } catch (SQLException ex) {
            for (String k : mv.keySet()) {
                System.out.println("[" + k + "][" + mv.get(k) + "]");
            }
            System.err.println("------------------------ Line No: " + lineNo);
            ex.printStackTrace();
        }
    }
}

From source file:edu.illinois.cs.cogcomp.transliteration.WikiTransliteration.java

public static HashMap<Production, Double> FindWeightedAlignmentsAverage(String word1, String word2,
        int maxSubstringLength1, int maxSubstringLength2, HashMap<Production, Double> probs,
        InternDictionary<String> internTable, Boolean weightByOthers, NormalizationMode normalization) {
    HashMap<Production, Double> weights = new HashMap<>();
    HashMap<Production, Double> weightCounts = new HashMap<>();
    //FindWeightedAlignmentsAverage(1, new List<Pair<String, String>>(), word1, word2, maxSubstringLength1, maxSubstringLength2, probs, weights, weightCounts, new HashMap<Pair<String, String>, Pair<double, double>>(), weightByOthers);
    FindWeightedAlignmentsAverage(1, new ArrayList<Production>(), word1, word2, maxSubstringLength1,
            maxSubstringLength2, probs, weights, weightCounts, weightByOthers);

    //CheckDictionary(weights);

    HashMap<Production, Double> weights2 = new HashMap<>(weights.size());
    for (Production wkey : weights.keySet())
        weights2.put(wkey, weights.get(wkey) == 0 ? 0 : weights.get(wkey) / weightCounts.get(wkey));
    weights = weights2;/* w ww .  j av  a  2s  . com*/

    return Normalize(word1, word2, weights, internTable, normalization);
}