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:fr.isen.browser5.Util.UrlLoader.java

private void load(String url, Object... args) {
    String method = null, action = null;
    HashMap<String, String> params = null;
    if (args.length == 3) {
        method = (String) args[0];
        action = (String) args[1];
        params = (HashMap<String, String>) args[2];
    }//from  www  .  j  a  v  a  2s  .c  o  m
    try {
        url = Str.checkProtocol(url);
        String urlParameters = "";
        if (method != null) {
            url = Str.removeLastSlash(url);
            if (action.startsWith("/")) {
                action = action.substring(1);
            }
            if (action.startsWith("http://") || action.startsWith("https://")) {
                url = action;
            } else {
                url += "/" + action;
            }

            int i = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlParameters += entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8");
                if (!(i++ == params.size() - 1)) {
                    urlParameters += "&";
                }
            }

            if (method.equals("GET")) {
                url += "?" + urlParameters;
            }
        } else {
            method = "GET";
        }

        System.out.println();
        System.out.println("Loading url: " + url);

        URL obj = new URL(url);
        connection = (HttpURLConnection) obj.openConnection();
        connection.setReadTimeout(10000);
        connection.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
        connection.addRequestProperty("User-Agent", "Lynx/2.8.8dev.3 libwww-FM/2.14 SSL-MM/1.4.1");
        connection.setRequestMethod(method);

        if (method.equals("POST")) {
            byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(postData.length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.write(postData);
            }
        }

        if (handleRedirects())
            return;

        handleConnectionResponse();
    } catch (IOException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ex.getMessage(), ex.getClass().getSimpleName(),
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.cloudera.impala.catalog.CatalogServiceCatalog.java

/**
 * Returns all user defined functions (aggregate and scalar) in the specified database.
 * Functions are not returned in a defined order.
 *//* www.j  av a2s .  c o  m*/
public List<Function> getFunctions(String dbName) throws DatabaseNotFoundException {
    Db db = getDb(dbName);
    if (db == null) {
        throw new DatabaseNotFoundException("Database does not exist: " + dbName);
    }

    // Contains map of overloaded function names to all functions matching that name.
    HashMap<String, List<Function>> dbFns = db.getAllFunctions();
    List<Function> fns = new ArrayList<Function>(dbFns.size());
    for (List<Function> fnOverloads : dbFns.values()) {
        for (Function fn : fnOverloads) {
            fns.add(fn);
        }
    }
    return fns;
}

From source file:org.montanafoodhub.base.get.ItemHub.java

protected HashMap<String, Item> readFromFile(Context context) {
    HashMap<String, Item> myItemMap = new HashMap<String, Item>();
    try {//  w w w.jav a  2s  .  c o  m
        // getItem the time the file was last changed here
        File myFile = new File(context.getFilesDir() + "/" + fileName);
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        String lastRefreshTSStr = sdf.format(myFile.lastModified());
        Log.w(HubInit.logTag, "Using file (" + fileName + ") last modified on : " + lastRefreshTSStr);
        lastRefreshTS = sdf.getCalendar();

        // create products from the file here
        InputStream inputStream = context.openFileInput(fileName);
        if (inputStream != null) {
            parseCSV(myItemMap, inputStream);
        }
        inputStream.close();
    } catch (FileNotFoundException e) {
        Log.e(HubInit.logTag, "File  (" + fileName + ") not found: " + e.toString());
    } catch (IOException e) {
        Log.e(HubInit.logTag, "Can not read file  (" + fileName + ") : " + e.toString());
    }
    Log.w(HubInit.logTag, "Number of items loaded: " + myItemMap.size());
    return myItemMap;
}

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

/**
 * Test method for 'java.util.HashMap.putAll(Map)'.
 *///w w w.  j a  va  2 s . c  o m
public void testPutAll() {
    HashMap<String, String> srcMap = new HashMap<String, String>();
    checkEmptyHashMapAssumptions(srcMap);

    srcMap.put(KEY_1, VALUE_1);
    srcMap.put(KEY_2, VALUE_2);
    srcMap.put(KEY_3, VALUE_3);

    // Make sure that the data is copied correctly
    HashMap<String, String> dstMap = new HashMap<String, String>();
    checkEmptyHashMapAssumptions(dstMap);

    dstMap.putAll(srcMap);
    assertEquals(srcMap.size(), dstMap.size());
    assertTrue(dstMap.containsKey(KEY_1));
    assertTrue(dstMap.containsValue(VALUE_1));
    assertFalse(dstMap.containsKey(KEY_1.toUpperCase(Locale.ROOT)));
    assertFalse(dstMap.containsValue(VALUE_1.toUpperCase(Locale.ROOT)));

    assertTrue(dstMap.containsKey(KEY_2));
    assertTrue(dstMap.containsValue(VALUE_2));
    assertFalse(dstMap.containsKey(KEY_2.toUpperCase(Locale.ROOT)));
    assertFalse(dstMap.containsValue(VALUE_2.toUpperCase(Locale.ROOT)));

    assertTrue(dstMap.containsKey(KEY_3));
    assertTrue(dstMap.containsValue(VALUE_3));
    assertFalse(dstMap.containsKey(KEY_3.toUpperCase(Locale.ROOT)));
    assertFalse(dstMap.containsValue(VALUE_3.toUpperCase(Locale.ROOT)));

    // Check that an empty map does not blow away the contents of the
    // destination map
    HashMap<String, String> emptyMap = new HashMap<String, String>();
    checkEmptyHashMapAssumptions(emptyMap);
    dstMap.putAll(emptyMap);
    assertTrue(dstMap.size() == srcMap.size());

    // Check that put all overwrite any existing mapping in the destination map
    srcMap.put(KEY_1, VALUE_2);
    srcMap.put(KEY_2, VALUE_3);
    srcMap.put(KEY_3, VALUE_1);

    dstMap.putAll(srcMap);
    assertEquals(dstMap.size(), srcMap.size());
    assertEquals(dstMap.get(KEY_1), VALUE_2);
    assertEquals(dstMap.get(KEY_2), VALUE_3);
    assertEquals(dstMap.get(KEY_3), VALUE_1);

    // Check that a putAll does adds data but does not remove it

    srcMap.put(KEY_4, VALUE_4);
    dstMap.putAll(srcMap);
    assertEquals(dstMap.size(), srcMap.size());
    assertTrue(dstMap.containsKey(KEY_4));
    assertTrue(dstMap.containsValue(VALUE_4));
    assertEquals(dstMap.get(KEY_1), VALUE_2);
    assertEquals(dstMap.get(KEY_2), VALUE_3);
    assertEquals(dstMap.get(KEY_3), VALUE_1);
    assertEquals(dstMap.get(KEY_4), VALUE_4);

    dstMap.putAll(dstMap);
}

From source file:org.powertac.tariffmarket.CapacityControlServiceTest.java

/**
 * Test method for {@link org.powertac.tariffmarket.CapacityControlService#activate(org.joda.time.Instant, int)}.
 *///from ww  w  .  j  a va 2  s. co m
@Test
public void testActivate() {
    // set up subscriptions
    TariffSubscription sub1 = tariffSubscriptionRepo.getSubscription(customer1, tariff);
    sub1.subscribe(100);
    TariffSubscription sub2 = tariffSubscriptionRepo.getSubscription(customer2, tariff);
    sub2.subscribe(200);

    // post a couple of economic controls
    EconomicControlEvent ece0 = new EconomicControlEvent(spec, 0.20, 0);
    EconomicControlEvent ece1 = new EconomicControlEvent(spec, 0.25, 1);
    capacityControl.postEconomicControl(ece0);
    capacityControl.postEconomicControl(ece1);

    // activate the capacity control
    capacityControl.activate(timeService.getCurrentTime(), 1);

    // capture calls to Accounting
    reset(mockAccounting);
    final HashMap<CustomerInfo, Object[]> answers = new HashMap<CustomerInfo, Object[]>();
    when(mockAccounting.addTariffTransaction(any(TariffTransaction.Type.class), any(Tariff.class),
            any(CustomerInfo.class), anyInt(), anyDouble(), anyDouble())).thenAnswer(new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) {
                    Object[] args = invocation.getArguments();
                    CustomerInfo customer = (CustomerInfo) args[2];
                    answers.put(customer, args);
                    return null;
                }
            });

    // now the customer model is primed. Both customers should be curtailed
    // by 20% in this timeslot.
    sub1.usePower(200);
    sub2.usePower(300);

    assertEquals("correct # of calls", 2, answers.size());
    Object[] args = answers.get(customer1);
    assertNotNull("customer1 included", args);
    assertEquals("correct arg count", 6, args.length);
    assertEquals("correct type", TariffTransaction.Type.CONSUME, (TariffTransaction.Type) args[0]);
    assertEquals("correct tariff", tariff, (Tariff) args[1]);
    assertEquals("correct kwh", -160.0, (Double) args[4], 1e-6);
    assertEquals("correct charge", 160.0 * 0.11, (Double) args[5], 1e-6);

    args = answers.get(customer2);
    assertNotNull("customer2 included", args);
    assertEquals("correct arg count", 6, args.length);
    assertEquals("correct type", TariffTransaction.Type.CONSUME, (TariffTransaction.Type) args[0]);
    assertEquals("correct tariff", tariff, (Tariff) args[1]);
    assertEquals("correct kwh", -240.0, (Double) args[4], 1e-6);
    assertEquals("correct charge", 240.0 * 0.11, (Double) args[5], 1e-6);

    // check regulation info
    assertEquals("correct regulation sub1", 40.0, sub1.getCurtailment(), 1e-6);
    assertEquals("correct regulation sub1", 60.0, sub2.getCurtailment(), 1e-6);
}

From source file:ec.coevolve.MultiPopCoevolutionaryEvaluatorExtra.java

@Override
void loadElites(final EvolutionState state, int whichSubpop) {
    Subpopulation subpop = state.population.subpops[whichSubpop];

    // Update hall of fame
    if (hallOfFame != null) {
        int best = 0;
        Individual[] oldinds = subpop.individuals;
        for (int x = 1; x < oldinds.length; x++) {
            if (betterThan(oldinds[x], oldinds[best])) {
                best = x;//  w ww.ja v a2 s. c o  m
            }
        }
        hallOfFame[whichSubpop].add((Individual) subpop.individuals[best].clone());
    }

    int index = 0;

    // Last champions
    if (lastChampions > 0) {
        for (int i = 1; i <= lastChampions && i <= hallOfFame[whichSubpop].size(); i++) {
            eliteIndividuals[whichSubpop][index++] = (Individual) hallOfFame[whichSubpop]
                    .get(hallOfFame[whichSubpop].size() - i).clone();
        }
    }

    double randChamps = randomChampions;

    // Novel champions
    if (novelChampions > 0) {
        Individual[] behaviourElite = behaviourElite(state, whichSubpop);
        for (int i = 0; i < behaviourElite.length; i++) {
            eliteIndividuals[whichSubpop][index++] = (Individual) behaviourElite[i].clone();
            //System.out.println(whichSubpop + "\t" + ((ExpandedFitness) behaviourElite[i].fitness).getFitnessScore());
        }
        randChamps = randomChampions + (novelChampions - behaviourElite.length);
    }

    // Random champions
    if (randChamps > 0) {
        // Choose random positions
        ArrayList<Integer> pos = new ArrayList<Integer>(hallOfFame[whichSubpop].size());
        for (int i = 0; i < hallOfFame[whichSubpop].size(); i++) {
            pos.add(i);
        }
        Collections.shuffle(pos);
        for (int i = 0; i < pos.size() && i < randChamps; i++) {
            eliteIndividuals[whichSubpop][index++] = (Individual) hallOfFame[whichSubpop].get(pos.get(i))
                    .clone();
        }
    }

    // NEAT Elite
    if (neatElite > 0) {
        NEATGeneticAlgorithm neat = ((NEATSubpop) subpop).getNEAT();
        if (!neat.getSpecies().specieList().isEmpty()) {
            HashMap<Integer, Individual> specieBests = new HashMap<Integer, Individual>(
                    neat.getSpecies().specieList().size() * 2);
            Chromosome[] genoTypes = neat.population().genoTypes();
            for (int i = 0; i < genoTypes.length; i++) {
                int specie = ((NEATChromosome) genoTypes[i]).getSpecieId();
                if (!specieBests.containsKey(specie)
                        || betterThan(subpop.individuals[i], specieBests.get(specie))) {
                    specieBests.put(specie, subpop.individuals[i]);
                }
            }
            Individual[] specBests = new Individual[specieBests.size()];
            specieBests.values().toArray(specBests);
            QuickSort.qsort(specBests, new EliteComparator2());
            for (int i = 0; i < specBests.length && i < neatElite; i++) {
                eliteIndividuals[whichSubpop][index++] = (Individual) specBests[i].clone();
            }
        }
    }

    // Fill remaining with the elite of the current pop
    int toFill = numElite - index;
    if (toFill == 1) { // Just one to place
        Individual best = subpop.individuals[0];
        for (int x = 1; x < subpop.individuals.length; x++) {
            if (betterThan(subpop.individuals[x], best)) {
                best = subpop.individuals[x];
            }
        }
        eliteIndividuals[whichSubpop][index++] = (Individual) best.clone();
    } else if (toFill > 1) {
        Individual[] orderedPop = Arrays.copyOf(subpop.individuals, subpop.individuals.length);
        QuickSort.qsort(orderedPop, new EliteComparator2());
        // load the top N individuals
        for (int j = 0; j < toFill; j++) {
            eliteIndividuals[whichSubpop][index++] = (Individual) orderedPop[j].clone();
        }
    }
}

From source file:com.testmax.framework.PerformerBase.java

protected void addUnitTestActionMonitor(String action, String assertname, String msg, boolean response) {
    String amsg = "";
    String assertresult = "";
    int index = 1;
    HashMap<String, String> testresult = new HashMap<String, String>();
    if (validatorMessage.get(action) != null) {
        testresult = validatorMessage.get(action);
        index = testresult.size() + 1;
    }//from ww w . ja  v  a2s. co  m
    if (response) {
        int totalPassed = (validatorOKCount.get(action) == null ? 0 : validatorOKCount.get(action)) + 1;
        validatorOKCount.put(action, totalPassed);
        amsg = (actionErrorMessage.get(action) == null ? "" : actionErrorMessage.get(action));
        actionErrorMessage.put(action, (amsg.equalsIgnoreCase("PASSED") ? "" : amsg)
                + "<br><font color=\"blue\" >PASSED </font> >>" + msg + "<br>");
        testresult.put("TEST-" + index + ": " + assertname, "PASSED -" + msg);
    } else {

        amsg = (actionErrorMessage.get(action) == null ? "" : actionErrorMessage.get(action));
        actionErrorMessage.put(action, (amsg.equalsIgnoreCase("PASSED") ? "" : amsg)
                + "<br><font color=\"red\" >FAILED </font> >>" + msg + "<br>");
        int totalError = (validatorErrorCount.get(action) == null ? 0 : validatorErrorCount.get(action)) + 1;
        validatorErrorCount.put(action, totalError);
        testresult.put("TEST-" + index + ": " + assertname, "FAILED -" + msg);
    }

    validatorMessage.put(action, testresult);

}

From source file:org.montanafoodhub.base.get.BuyerHub.java

protected HashMap<String, Buyer> readFromFile(Context context) {
    HashMap<String, Buyer> myBuyerMap = new HashMap<String, Buyer>();
    try {/*from   w w w .  j  a v  a 2 s . c  o m*/
        // getItem the time the file was last changed here
        File myFile = new File(context.getFilesDir() + "/" + fileName);
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        String lastRefreshTSStr = sdf.format(myFile.lastModified());
        Log.w(HubInit.logTag, "Using file (" + fileName + ") last modified on : " + lastRefreshTSStr);
        lastRefreshTS = sdf.getCalendar();

        // create products from the file here
        InputStream inputStream = context.openFileInput(fileName);
        if (inputStream != null) {
            parseCSV(myBuyerMap, inputStream);
        }
        inputStream.close();
    } catch (FileNotFoundException e) {
        Log.e(HubInit.logTag, "File  (" + fileName + ") not found: " + e.toString());
    } catch (IOException e) {
        Log.e(HubInit.logTag, "Can not read file  (" + fileName + ") : " + e.toString());
    }
    Log.w(HubInit.logTag, "Number of buyers loaded: " + myBuyerMap.size());
    return myBuyerMap;
}

From source file:org.montanafoodhub.base.get.CertificationHub.java

protected HashMap<String, Certification> readFromFile(Context context) {
    HashMap<String, Certification> myCertificationMap = new HashMap<String, Certification>();
    try {/*from  w ww.  j  a va  2  s  .  c o m*/
        // getItem the time the file was last changed here
        File myFile = new File(context.getFilesDir() + "/" + fileName);
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        String lastRefreshTSStr = sdf.format(myFile.lastModified());
        Log.w(HubInit.logTag, "Using file (" + fileName + ") last modified on : " + lastRefreshTSStr);
        lastRefreshTS = sdf.getCalendar();

        // create products from the file here
        InputStream inputStream = context.openFileInput(fileName);
        if (inputStream != null) {
            parseCSV(myCertificationMap, inputStream);
        }
        inputStream.close();
    } catch (FileNotFoundException e) {
        Log.e(HubInit.logTag, "File  (" + fileName + ") not found: " + e.toString());
    } catch (IOException e) {
        Log.e(HubInit.logTag, "Can not read file  (" + fileName + ") : " + e.toString());
    }
    Log.w(HubInit.logTag, "Number of certifications loaded: " + myCertificationMap.size());
    return myCertificationMap;
}