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:com.google.gwt.emultest.java.util.HashMapTest.java

public void testAddEqualKeys() {
    final HashMap<Number, Object> expected = new HashMap<Number, Object>();
    assertEquals(expected.size(), 0);
    iterateThrough(expected);//from  www.ja  v a2s . c  o  m
    expected.put(new Long(45), new Object());
    assertEquals(expected.size(), 1);
    iterateThrough(expected);
    expected.put(new Integer(45), new Object());
    assertNotSame(new Integer(45), new Long(45));
    assertEquals(expected.size(), 2);
    iterateThrough(expected);
}

From source file:com.sfs.whichdoctor.analysis.AgedDebtorsAnalysisDAOImpl.java

/**
 * Load groupings.//from  w  w  w.ja v  a  2  s  .c  o  m
 *
 * @param analysis the analysis
 * @return the aged debtors analysis bean
 */
private AgedDebtorsAnalysisBean loadGroupings(final AgedDebtorsAnalysisBean analysis) {

    HashMap<Integer, AgedDebtorsRecord> records = buildRecordMap(analysis);

    HashMap<Integer, ReceiptBean> lastReceipts = loadLastReceipts(analysis);

    TreeMap<String, AgedDebtorsGrouping> groupings = new TreeMap<String, AgedDebtorsGrouping>();

    // If there are no records then there is no need to perform any searches
    if (records.size() > 0) {
        // Loop through these for the different periods and in total
        for (Integer periodId : analysis.getPeriods().keySet()) {

            AgedDebtorsPeriod period = analysis.getPeriods().get(periodId);

            for (String type : types) {

                dataLogger.debug("Performing lookup for " + type);

                Collection<AgedDebtorsRecord> results = performLookup(analysis, period, type);

                for (AgedDebtorsRecord result : results) {

                    int guid = result.getPersonGUID();
                    if (result.getOrganisationGUID() > 0) {
                        guid = result.getOrganisationGUID();
                    }

                    String groupName = analysis.getGroupName(guid);

                    AgedDebtorsGrouping grouping = new AgedDebtorsGrouping();
                    grouping.setName(groupName);
                    if (groupings.containsKey(groupName)) {
                        grouping = groupings.get(groupName);
                    }

                    dataLogger.debug("Processing result for GUID: " + guid + ", "
                            + Formatter.toCurrency(result.getOutstandingDebitValue()));

                    AgedDebtorsRecord record = records.get(guid);

                    AgedDebtorsPeriod periodResult = new AgedDebtorsPeriod(period);
                    if (record.getPeriodBreakdown().containsKey(periodId)) {
                        periodResult = record.getPeriodBreakdown().get(periodId);
                    }

                    if (StringUtils.equalsIgnoreCase(type, "debit")) {
                        periodResult.setOutstandingDebitValue(result.getOutstandingDebitValue());

                        // Update the running total for the record
                        record.setOutstandingDebitValue(
                                record.getOutstandingDebitValue() + result.getOutstandingDebitValue());

                        // Update the running total for the period
                        period.setOutstandingDebitValue(
                                period.getOutstandingDebitValue() + result.getOutstandingDebitValue());
                    }
                    if (StringUtils.equalsIgnoreCase(type, "credit")) {
                        periodResult.setUnallocatedCreditValue(result.getOutstandingDebitValue());

                        // Update the running total for the record
                        record.setUnallocatedCreditValue(
                                record.getUnallocatedCreditValue() + result.getOutstandingDebitValue());

                        // Update the running total for the period
                        period.setUnallocatedCreditValue(
                                period.getUnallocatedCreditValue() + result.getOutstandingDebitValue());
                    }
                    if (StringUtils.equalsIgnoreCase(type, "refund")) {
                        periodResult.setUnallocatedRefundValue(result.getOutstandingDebitValue());

                        // Update the running total for the record
                        record.setUnallocatedRefundValue(
                                record.getUnallocatedRefundValue() + result.getOutstandingDebitValue());

                        // Update the running total for the period
                        period.setUnallocatedRefundValue(
                                period.getUnallocatedRefundValue() + result.getOutstandingDebitValue());
                    }
                    if (StringUtils.equalsIgnoreCase(type, "receipt")) {
                        periodResult.setUnallocatedReceiptValue(result.getOutstandingDebitValue());

                        // Update the running total for the record
                        record.setUnallocatedReceiptValue(
                                record.getUnallocatedReceiptValue() + result.getOutstandingDebitValue());

                        // Update the running total for the period
                        period.setUnallocatedReceiptValue(
                                period.getUnallocatedReceiptValue() + result.getOutstandingDebitValue());
                    }

                    // Set the last receipt if one exists for this record
                    if (lastReceipts.containsKey(guid)) {
                        record.setLastReceipt(lastReceipts.get(guid));
                    }

                    record.getPeriodBreakdown().put(periodId, periodResult);
                    grouping.getRecords().put(analysis.getOrderKey(guid), record);
                    groupings.put(groupName, grouping);
                }
            }
            analysis.getPeriods().put(periodId, period);
        }
    }
    analysis.setGroupings(processGroups(groupings, analysis.getShowZeroBalances()));

    return analysis;
}

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

private void iterateThrough(final HashMap<?, ?> expected) {
    Iterator<?> iter = expected.entrySet().iterator();
    for (int i = 0; i < expected.size(); i++) {
        iter.next();/*from   ww w.j  a v a  2 s . c  o  m*/
    }
}

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

public void testClone() {
    HashMap<String, String> srcMap = new HashMap<String, String>();
    checkEmptyHashMapAssumptions(srcMap);

    HashMap<String, String> dstMap = cloneMap(srcMap);
    assertNotNull(dstMap);// w  ww .ja va2 s  . c  o m
    assertEquals(dstMap.size(), srcMap.size());
    // assertTrue(dstMap.values().toArray().equals(srcMap.values().toArray()));
    assertTrue(dstMap.keySet().equals(srcMap.keySet()));
    assertTrue(dstMap.entrySet().equals(srcMap.entrySet()));

    // Check non-empty clone behavior
    srcMap.put(KEY_1, VALUE_1);
    srcMap.put(KEY_2, VALUE_2);
    srcMap.put(KEY_3, VALUE_3);
    dstMap = cloneMap(srcMap);
    assertNotNull(dstMap);
    assertEquals(dstMap.size(), srcMap.size());

    assertTrue(dstMap.keySet().equals(srcMap.keySet()));

    assertTrue(dstMap.entrySet().equals(srcMap.entrySet()));
}

From source file:mtmo.test.mediadrm.MainActivity.java

private void setupDrmProcessButton(final int appMode) {
    final Button btnRegistration = (Button) findViewById(R.id.btn_registration);
    final Button btnSaveLicense = (Button) findViewById(R.id.btn_license);
    final Button btnDeregistration = (Button) findViewById(R.id.btn_deregistration);
    final Button btnCheckRights = (Button) findViewById(R.id.btn_check_rights);
    final Button btnRemoveRights = (Button) findViewById(R.id.btn_remove_rights);
    final Button btnStatus = (Button) findViewById(R.id.btn_check_regist);

    if (btnRegistration != null) {
        btnRegistration.setOnClickListener(new OnClickListener() {
            @Override/*from  www  .ja  v a  2s  .  c  om*/
            public void onClick(View v) {
                mLogger.enter("requeseted registration...");

                final TaskInfo taskInfo = new TaskInfo(TaskType.REGISTRATION, mAccountId, mServiceId,
                        mCurrentATKNFilePath);
                mHandler.post(new TaskStarter(taskInfo));
            }
        });
    }
    if (btnSaveLicense != null) {
        btnSaveLicense.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLogger.d("requeseted getting License...");
                final TaskInfo taskInfo = new TaskInfo(TaskType.LICENSE, mAccountId, mServiceId,
                        mCurrentATKNFilePath);
                mHandler.post(new TaskStarter(taskInfo));
            }
        });
    }
    if (btnDeregistration != null) {
        btnDeregistration.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLogger.d("requeseted deregistration...");
                final TaskInfo taskInfo = new TaskInfo(TaskType.DEREGISTRATION, mAccountId, mServiceId,
                        mCurrentATKNFilePath);
                mHandler.post(new TaskStarter(taskInfo));
            }
        });
    }
    if (btnCheckRights != null) {
        btnCheckRights.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLogger.d("requeseted check License...");
                TextView log = (TextView) findViewById(R.id.log);
                byte[] sessionId = null;
                MediaDrm mediaDrm = null;
                byte[] contentData = null;
                log.setText("");

                try {
                    mediaDrm = new MediaDrm(Constants.MBB_UUID);
                    sessionId = mediaDrm.openSession();

                    switch (appMode) {
                    case Constants.APP_MODE_ABS:
                        ABSContentInfo absContentInfo = getABSContentInfo();
                        contentData = Utils.readPsshDataFromFile(true);
                        mediaDrm.restoreKeys(sessionId,
                                InitData.getPSSHTableForAndroid(contentData, absContentInfo.getVideoKid()));
                        break;
                    case Constants.APP_MODE_OFFLINE:
                        contentData = Utils.readIPMPDataFromFile(true);
                        mediaDrm.restoreKeys(sessionId, InitData.getIPMPTableForAndroid(contentData));
                        break;
                    default:
                        Toast.makeText(mContext, "Unknown App Mode", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    HashMap<String, String> infoMap = mediaDrm.queryKeyStatus(sessionId);

                    if (infoMap != null && infoMap.size() > 0) {
                        StringBuilder sb = new StringBuilder();
                        Iterator<String> iterator = infoMap.keySet().iterator();
                        log.setText("");
                        Time time = new Time();
                        while (iterator.hasNext()) {
                            String name = iterator.next();
                            time.set(Long.valueOf(infoMap.get(name)));
                            mLogger.d("\t" + name + " = " + infoMap.get(name) + " [" + time.format2445() + "]");
                            sb.append(
                                    "\n\t" + name + " = " + infoMap.get(name) + " [" + time.format2445() + "]");
                        }
                        log.append(sb);
                    }
                    mediaDrm.closeSession(sessionId);
                    sessionId = null;
                    Toast.makeText(MainActivity.this, "queryKeyStatus finished", Toast.LENGTH_LONG).show();
                    return;
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (UnsupportedSchemeException e) {
                    e.printStackTrace();
                } catch (NotProvisionedException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mediaDrm.closeSession(sessionId);
                sessionId = null;
                Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_LONG).show();
            }
        });
    }
    if (btnRemoveRights != null) {
        btnRemoveRights.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLogger.d("requeseted removing License...");
                Toast.makeText(MainActivity.this, "Not implementation", Toast.LENGTH_LONG).show();
            }
        });
    }
    if (btnStatus != null) {
        btnStatus.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLogger.enter("Check registration Status...");

                RequestParser parser = null;
                MediaDrm mediaDrm = null;
                byte[] sessionid = null;
                HashMap<String, String> optionalParameters = null;
                try {
                    mediaDrm = new MediaDrm(Constants.MBB_UUID);
                    sessionid = mediaDrm.openSession();
                    KeyRequest keyRequest = mediaDrm.getKeyRequest(sessionid,
                            InitData.getPropertyTableForAndroid(Constants.QUERY_NAME_REGISTERED_STATE,
                                    Utils.accountIdToMarlinFormat(mAccountId), mServiceId),
                            Constants.REQUEST_MIMETYPE_QUERY_PROPERTY, MediaDrm.KEY_TYPE_OFFLINE,
                            optionalParameters);
                    parser = new RequestParser(keyRequest.getData());

                    if (parser.parse()) {
                        Toast.makeText(MainActivity.this, parser.getProperty(), Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_LONG).show();
                    }
                    return;
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (UnsupportedSchemeException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (NotProvisionedException e) {
                    e.printStackTrace();
                }
                Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_LONG).show();
            }
        });
    }
}

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  w w.j a  v  a  2  s  . c o  m
}

From source file:com.yahoo.ycsb.db.PostgreSQLJsonbClient.java

private String getJsonString(HashMap<String, ByteIterator> values) {
    StringBuilder builder = new StringBuilder("{");
    int count = 0;
    for (Map.Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) {
        builder.append("\"" + entry.getKey() + "\":");
        builder.append("\"" + StringEscapeUtils.escapeJson(entry.getValue()) + "\"");
        if (count < values.size() - 1) {
            builder.append(",");
        }/* w  w  w . j a v  a2  s  . c  o m*/
        count++;
    }
    builder.append("}");

    return builder.toString();
}

From source file:de.tud.kom.p2psim.impl.skynet.visualization.SkyNetVisualization.java

public void updateDisplayedMetrics(long time, HashMap<String, MetricsAggregate> simulatorMetrics,
        HashMap<String, MetricsAggregate> rootMetrics/* , double nodeCounter */) {
    if (activated && displayedMetrics.size() > 0) {
        Iterator<String> nameIter = simulatorMetrics.keySet().iterator();
        String name = null;/*from   www .  j av a 2  s  .co  m*/
        while (nameIter.hasNext()) {
            name = nameIter.next();
            if (displayedMetrics.containsKey(name)) {
                DeviationSet[] values = null;
                if (rootMetrics.size() > 0) {
                    DeviationSet[] temp = { new DeviationSet(simulatorMetrics.get(name).getAverage()),
                            new DeviationSet(rootMetrics.get(name).getAverage(),
                                    rootMetrics.get(name).getStandardDeviation()),
                            new DeviationSet(rootMetrics.get(name).getMinimum()),
                            new DeviationSet(rootMetrics.get(name).getMaximum()) };
                    values = temp;
                } else {
                    DeviationSet[] temp = { new DeviationSet(simulatorMetrics.get(name).getAverage()),
                            new DeviationSet(0), new DeviationSet(0), new DeviationSet(0), };
                    values = temp;
                }
                String[] metricNames = { "Real " + name, "Measured " + name, "Min_Measured" + name,
                        "Max_Measured" + name };

                MetricsPlot temp = displayedMetrics.remove(name);
                temp.updatePlot(name, new DataSet(VisualizationType.Metric, time / 1000, values, metricNames));
                displayedMetrics.put(name, temp);
                updatePlotInWindow(time, name);
            }
        }
        validate();
        repaint();
    }
}

From source file:edu.caltech.ipac.firefly.server.util.ipactable.DataGroupReader.java

public static DataGroup getEnumValues(File inf, int cutoffPoint) throws IOException {

    TableDef tableMeta = IpacTableUtil.getMetaInfo(inf);
    List<DataType> cols = tableMeta.getCols();

    HashMap<DataType, List<String>> enums = new HashMap<DataType, List<String>>();
    ArrayList<DataType> workList = new ArrayList<DataType>();

    for (DataType dt : cols) {
        if (dt.getDataType().isAssignableFrom(Float.class) || dt.getDataType().isAssignableFrom(Double.class)) {
            continue;
        }//  www .jav a 2s.  c  om
        enums.put(dt, new ArrayList<String>());
        workList.add(dt);
    }
    DataGroup dg = new DataGroup(null, cols);

    BufferedReader reader = new BufferedReader(new FileReader(inf), IpacTableUtil.FILE_IO_BUFFER_SIZE);
    String line = null;
    int lineNum = 0;
    try {
        line = reader.readLine();
        lineNum++;
        while (line != null) {
            DataObject row = IpacTableUtil.parseRow(dg, line, false);
            if (row != null) {
                List<DataType> ccols = new ArrayList<DataType>(workList);
                for (DataType dt : ccols) {
                    String v = String.valueOf(row.getDataElement(dt));
                    List<String> l = enums.get(dt);
                    if (l == null || l.size() >= cutoffPoint
                            || (dt.getDataType().isAssignableFrom(String.class) && v.length() > 20)) {
                        workList.remove(dt);
                        enums.remove(dt);
                    } else if (!l.contains(v)) {
                        l.add(v);
                    }
                }
            }
            line = reader.readLine();
            lineNum++;
            if (enums.size() == 0) {
                break;
            }
        }
    } catch (Exception e) {
        String msg = e.getMessage() + "<br>on line " + lineNum + ": " + line;
        if (msg.length() > 128)
            msg = msg.substring(0, 128) + "...";
        logger.error(e, "on line " + lineNum + ": " + line);
        throw new IOException(msg);
    } finally {
        reader.close();
    }

    if (enums.size() > 0) {
        for (DataType dt : enums.keySet()) {
            List<String> values = enums.get(dt);
            Collections.sort(values, DataGroupUtil.getComparator(dt));
            dg.addAttribute(
                    TemplateGenerator.createAttributeKey(TemplateGenerator.Tag.ITEMS_TAG, dt.getKeyName()),
                    StringUtils.toString(values, ","));
        }
    }

    return dg;
}

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

public void testHashMapMap() {
    HashMap<Integer, Integer> srcMap = new HashMap<Integer, Integer>();
    assertNotNull(srcMap);//  w ww  .  j  a va  2s  .c o  m
    checkEmptyHashMapAssumptions(srcMap);

    srcMap.put(INTEGER_1, INTEGER_11);
    srcMap.put(INTEGER_2, INTEGER_22);
    srcMap.put(INTEGER_3, INTEGER_33);

    HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>(srcMap);
    assertFalse(hashMap.isEmpty());
    assertTrue(hashMap.size() == SIZE_THREE);

    Collection<Integer> valColl = hashMap.values();
    assertTrue(valColl.contains(INTEGER_11));
    assertTrue(valColl.contains(INTEGER_22));
    assertTrue(valColl.contains(INTEGER_33));

    Collection<Integer> keyColl = hashMap.keySet();
    assertTrue(keyColl.contains(INTEGER_1));
    assertTrue(keyColl.contains(INTEGER_2));
    assertTrue(keyColl.contains(INTEGER_3));
}