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:com.impetus.ankush.common.dao.impl.GenericDaoJpa.java

/**
 * Flatten parameter list./*w  w w. j a va2  s  .c  o  m*/
 * 
 * @param parameterMaps
 *            the parameter maps
 * @return the list
 */
private List<Object> flattenParameterList(List<LinkedHashMap<String, Object>> parameterMaps) {
    List<Object> parameterList = new ArrayList<Object>();
    for (HashMap<String, Object> parameterMap : parameterMaps) {
        for (Entry<String, Object> entry : parameterMap.entrySet()) {
            parameterList.add(entry.getValue());
        }
    }
    return parameterList;
}

From source file:de.audiogrid.devices.rs232.service.SerialIO.java

private void setDeviceData(RS232Device device, HashMap<String, String> formattedResult) {
    for (Map.Entry<String, String> entry : formattedResult.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        device.addContent(key, value);//  w  w w . java 2  s.co  m
    }
}

From source file:ch.unibas.fittingwizard.application.tools.LPunParser.java

public ArrayList<AtomType> parse(File lpunFile) {
    List<String> lines;
    try {/*from www  . j  a  v  a 2s  .  c o m*/
        lines = FileUtils.readLines(lpunFile);
    } catch (IOException e) {
        throw new RuntimeException("Could not read file " + lpunFile.getAbsolutePath(), e);
    }

    lines = removeHeader(lines);
    lines = removeFooter(lines);

    HashMap<String, ArrayList<Integer>> atomTypePositions = new HashMap<>();

    int idxCharge = 0;
    for (int i = 0; i + 2 < lines.size(); i += 3) {
        String type = lines.get(i).trim().split("\\s+")[0].trim();

        ArrayList<Integer> indices = atomTypePositions.get(type);
        if (indices == null) {
            indices = new ArrayList<>();
            atomTypePositions.put(type, indices);
        }
        indices.add(idxCharge);

        idxCharge++;
    }

    ArrayList<AtomType> charges = new ArrayList<>();
    for (Map.Entry<String, ArrayList<Integer>> entry : atomTypePositions.entrySet()) {
        ArrayList<Integer> indices = entry.getValue();
        int[] array = new int[indices.size()];
        for (int i = 0; i < indices.size(); i++)
            array[i] = indices.get(i);
        AtomType atomType = new AtomType(entry.getKey(), array);
        charges.add(atomType);
    }

    return charges;
}

From source file:edu.jhuapl.dorset.agents.StockAgent.java

protected CompanyInfo findStockSymbol(String stockCompanyName) {
    CompanyInfo companyInfo = null;/*from   w w  w  .  ja v  a  2s .c o  m*/
    ArrayList<String> regexMatches = new ArrayList<String>();

    if (this.stockSymbolMap.get(stockCompanyName) != null) {
        companyInfo = this.stockSymbolMap.get(stockCompanyName);

    } else {
        String regex = "\\b" + stockCompanyName + "\\b";

        Pattern pat = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

        for (Map.Entry<String, CompanyInfo> entry : stockSymbolMap.entrySet()) {
            Matcher matcher = pat.matcher(entry.getKey());

            if (matcher.find()) {
                regexMatches.add(entry.getKey());
            }
        }

        if (regexMatches.size() == 0) {
            companyInfo = null;
        } else if (regexMatches.size() == 1) {
            companyInfo = this.stockSymbolMap.get(regexMatches.get(0));

        } else {
            int distance;
            HashMap<String, Integer> matchDistanceMap = new HashMap<String, Integer>();
            for (int i = 0; i < regexMatches.size(); i++) {
                distance = (StringUtils.getLevenshteinDistance(regexMatches.get(i), stockCompanyName));
                matchDistanceMap.put(regexMatches.get(i), distance);
            }

            Entry<String, Integer> minDistancePair = null;
            for (Entry<String, Integer> entry : matchDistanceMap.entrySet()) {
                if (minDistancePair == null || minDistancePair.getValue() > entry.getValue()) {
                    minDistancePair = entry;
                }
            }

            companyInfo = this.stockSymbolMap.get(minDistancePair.getKey());

        }

    }

    return companyInfo;
}

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

/**
 *  Store Q values to file using JSON structure.
 *///w  w w.ja v  a  2 s  .com
public void storeQ() {
    String textQ = "";
    //      JSONArray actionValueArray=new JSONArray();
    JSONObject actionValuePair = new JSONObject();

    JSONObject actionsStatePair = new JSONObject();
    //      JSONArray statesArray= new JSONArray();
    try {
        Iterator<Entry<String, HashMap<String, Double>>> itS = this.Q.entrySet().iterator();
        while (itS.hasNext()) {
            Entry<String, HashMap<String, Double>> pairs = itS.next();
            HashMap<String, Double> tempA = pairs.getValue();
            Iterator<Entry<String, Double>> itA = tempA.entrySet().iterator();
            double val = 0;
            //            System.out.print("State("+pairs.getKey()+") actions: ");
            actionValuePair = new JSONObject();
            while (itA.hasNext()) {
                Entry<String, Double> pairsA = itA.next();
                val = pairsA.getValue();
                actionValuePair.put(pairsA.getKey(), val);
            }
            //            System.out.println(actionsStatePair+" "+pairs.getKey()+" "+actionValuePair);
            actionsStatePair.put(pairs.getKey(), actionValuePair);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    //use buffering
    Writer output;
    try {
        output = new BufferedWriter(new FileWriter(fileName));

        try {
            //FileWriter always assumes default encoding is OK!
            output.write(actionsStatePair.toString());
        } finally {
            output.close();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    //      System.out.println("------ Stored Q -------");
    //      System.out.println("Q: "+actionsStatePair.toString());
    //      System.out.println("----------------------------");
}

From source file:gaffer.store.Store.java

protected void validateSchemas() {
    boolean valid = validateTwoSetsContainSameElements(getDataSchema().getEdgeGroups(),
            getStoreSchema().getEdgeGroups(), "edges")
            && validateTwoSetsContainSameElements(getDataSchema().getEntityGroups(),
                    getStoreSchema().getEntityGroups(), "entities");

    if (!valid) {
        throw new SchemaException(
                "ERROR: the store schema did not pass validation because the store schema and data schema contain different numbers of elements. Please check the logs for more detailed information");
    }/*from w w w  .  j  ava2  s . c  o  m*/

    for (String group : getDataSchema().getEdgeGroups()) {
        valid &= validateTwoSetsContainSameElements(getDataSchema().getEdge(group).getProperties(),
                getStoreSchema().getEdge(group).getProperties(), "properties in the edge \"" + group + "\"");
    }

    for (String group : getDataSchema().getEntityGroups()) {
        valid &= validateTwoSetsContainSameElements(getDataSchema().getEntity(group).getProperties(),
                getStoreSchema().getEntity(group).getProperties(),
                "properties in the entity \"" + group + "\"");
    }

    if (!valid) {
        throw new SchemaException(
                "ERROR: the store schema did not pass validation because at least one of the elements in the store schema and data schema contain different numbers of properties. Please check the logs for more detailed information");
    }
    HashMap<String, StoreElementDefinition> storeSchemaElements = new HashMap<>();
    storeSchemaElements.putAll(getStoreSchema().getEdges());
    storeSchemaElements.putAll(getStoreSchema().getEntities());
    for (Map.Entry<String, StoreElementDefinition> storeElementDefinitionEntry : storeSchemaElements
            .entrySet()) {
        DataElementDefinition dataElementDefinition = getDataSchema()
                .getElement(storeElementDefinitionEntry.getKey());
        for (String propertyName : storeElementDefinitionEntry.getValue().getProperties()) {
            Class propertyClass = dataElementDefinition.getPropertyClass(propertyName);
            Serialisation serialisation = storeElementDefinitionEntry.getValue().getProperty(propertyName)
                    .getSerialiser();

            if (!serialisation.canHandle(propertyClass)) {
                valid = false;
                LOGGER.error("Store schema serialiser for property '" + propertyName + "' in the group '"
                        + storeElementDefinitionEntry.getKey()
                        + "' cannot handle property found in the data schema");
            }
        }
    }
    if (!valid) {
        throw new SchemaException(
                "ERROR: Store schema property serialiser cannot handle a property in the data schema");
    }

}

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  w w  . ja v  a2s .  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:ch.cyberduck.core.spectra.SpectraReadFeatureTest.java

@Test
public void testSPECTRA66() throws Exception {
    final Host host = new Host(new SpectraProtocol() {
        @Override//w w w  .j  av  a  2  s . c o m
        public Scheme getScheme() {
            return Scheme.http;
        }
    }, System.getProperties().getProperty("spectra.hostname"),
            Integer.valueOf(System.getProperties().getProperty("spectra.port")),
            new Credentials(System.getProperties().getProperty("spectra.user"),
                    System.getProperties().getProperty("spectra.key")));
    final SpectraSession session = new SpectraSession(host, new DisabledX509TrustManager(),
            new DefaultX509KeyManager());
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path container = new Path("CYBERDUCK-SPECTRA-67", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final HashMap<Path, TransferStatus> files = new HashMap<>();
    for (int i = 1; i < 100; i++) {
        files.put(new Path(container, String.format("test-%d.f", i), EnumSet.of(Path.Type.file)),
                new TransferStatus());
    }
    final SpectraBulkService bulk = new SpectraBulkService(session);
    final Set<UUID> uuid = bulk.pre(Transfer.Type.download, files, new DisabledConnectionCallback());
    assertNotNull(uuid);
    assertFalse(uuid.isEmpty());
    assertEquals(1, uuid.size());
    for (Map.Entry<Path, TransferStatus> entry : files.entrySet()) {
        final InputStream in = new SpectraReadFeature(session).read(entry.getKey(), entry.getValue(),
                new DisabledConnectionCallback());
        assertNotNull(in);
        IOUtils.closeQuietly(in);
    }
    session.close();
}

From source file:com.ethercamp.harmony.service.BlockchainInfoService.java

@Scheduled(fixedRate = 2000)
private void doUpdateNetworkInfo() {
    final NetworkInfoDTO info = new NetworkInfoDTO(channelManager.getActivePeers().size(),
            NetworkInfoDTO.SyncStatusDTO.instanceOf(syncManager.getSyncStatus()), config.listenPort(), true);

    final HashMap<String, Integer> miners = new HashMap<>();
    lastBlocksForHashRate.stream().forEach(b -> {
        String minerAddress = Hex.toHexString(b.getCoinbase());
        int count = miners.containsKey(minerAddress) ? miners.get(minerAddress) : 0;
        miners.put(minerAddress, count + 1);
    });//from  w  ww.  j a  v  a  2 s.  c o  m

    final List<MinerDTO> minersList = miners.entrySet().stream()
            .map(entry -> new MinerDTO(entry.getKey(), entry.getValue()))
            .sorted((a, b) -> Integer.compare(b.getCount(), a.getCount())).limit(3).collect(toList());
    info.getMiners().addAll(minersList);

    networkInfo.set(info);

    clientMessageService.sendToTopic("/topic/networkInfo", info);
}

From source file:net.dahanne.gallery.g2.java.client.business.G2Client.java

public int sendImageToGallery(String galleryUrl, int albumName, File imageFile, String imageName,
        String summary, String description) throws GalleryConnectionException {

    int imageCreatedName = 0;

    MultipartEntity multiPartEntity = createMultiPartEntityForSendImageToGallery(albumName, imageFile,
            imageName, summary, description);
    HashMap<String, String> properties = sendCommandToGallery(galleryUrl, null, multiPartEntity);

    for (Entry<String, String> entry : properties.entrySet()) {
        if (entry.getKey().equals(ITEM_NAME)) {
            imageCreatedName = new Integer(entry.getValue()).intValue();
            break;
        }//w w  w  .  j  a  va2s .c o m
        if (entry.getValue().contains(FAILED)) {
            throw new GalleryConnectionException(UPLOAD_FAILED);
        }
    }
    return imageCreatedName;
}