Example usage for java.util TreeMap containsValue

List of usage examples for java.util TreeMap containsValue

Introduction

In this page you can find the example usage for java.util TreeMap containsValue.

Prototype

public boolean containsValue(Object value) 

Source Link

Document

Returns true if this map maps one or more keys to the specified value.

Usage

From source file:Main.java

public static void main(String[] args) {
    TreeMap<String, String> treeMap = new TreeMap<String, String>();

    treeMap.put("1", "One");
    treeMap.put("2", "Two");
    treeMap.put("3", "Three");

    System.out.println(treeMap.containsValue("Three"));
}

From source file:Main.java

public static void main(String[] args) {

    TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();

    // populating tree map
    treemap.put(2, "two");
    treemap.put(1, "one");
    treemap.put(3, "three");
    treemap.put(6, "six");
    treemap.put(5, "from java2s.com");

    System.out.println("Checking value");
    System.out.println("'three' exists: " + treemap.containsValue("three"));
}

From source file:TwitterClustering.java

public static void main(String[] args) throws FileNotFoundException, IOException {
    // TODO code application logic here

    File outFile = new File(args[3]);
    Scanner s = new Scanner(new File(args[1])).useDelimiter(",");
    JSONParser parser = new JSONParser();
    Set<Cluster> clusterSet = new HashSet<Cluster>();
    HashMap<String, Tweet> tweets = new HashMap();
    FileWriter fw = new FileWriter(outFile.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);

    // init/*from w  w  w  .  j  a v  a 2 s. com*/
    try {

        Object obj = parser.parse(new FileReader(args[2]));

        JSONArray jsonArray = (JSONArray) obj;

        for (int i = 0; i < jsonArray.size(); i++) {

            Tweet twt = new Tweet();
            JSONObject jObj = (JSONObject) jsonArray.get(i);
            String text = jObj.get("text").toString();

            long sum = 0;
            for (int y = 0; y < text.toCharArray().length; y++) {

                sum += (int) text.toCharArray()[y];
            }

            String[] token = text.split(" ");
            String tID = jObj.get("id").toString();

            Set<String> mySet = new HashSet<String>(Arrays.asList(token));
            twt.setAttributeValue(sum);
            twt.setText(mySet);
            twt.setTweetID(tID);
            tweets.put(tID, twt);

        }

        // preparing initial clusters
        int i = 0;
        while (s.hasNext()) {
            String id = s.next();// id
            Tweet t = tweets.get(id.trim());
            clusterSet.add(new Cluster(i + 1, t, new LinkedList()));
            i++;
        }

        Iterator it = tweets.entrySet().iterator();

        for (int l = 0; l < 2; l++) { // limit to 25 iterations

            while (it.hasNext()) {
                Map.Entry me = (Map.Entry) it.next();

                // calculate distance to each centroid
                Tweet p = (Tweet) me.getValue();
                HashMap<Cluster, Float> distMap = new HashMap();

                for (Cluster clust : clusterSet) {

                    distMap.put(clust, jaccardDistance(p.getText(), clust.getCentroid().getText()));
                }

                HashMap<Cluster, Float> sorted = (HashMap<Cluster, Float>) sortByValue(distMap);

                sorted.keySet().iterator().next().getMembers().add(p);

            }

            // calculate new centroid and update Clusterset
            for (Cluster clust : clusterSet) {

                TreeMap<String, Long> tDistMap = new TreeMap();

                Tweet newCentroid = null;
                Long avgSumDist = new Long(0);
                for (int j = 0; j < clust.getMembers().size(); j++) {

                    avgSumDist += clust.getMembers().get(j).getAttributeValue();
                    tDistMap.put(clust.getMembers().get(j).getTweetID(),
                            clust.getMembers().get(j).getAttributeValue());
                }
                if (clust.getMembers().size() != 0) {
                    avgSumDist /= (clust.getMembers().size());
                }

                ArrayList<Long> listValues = new ArrayList<Long>(tDistMap.values());

                if (tDistMap.containsValue(findClosestNumber(listValues, avgSumDist))) {
                    // found closest
                    newCentroid = tweets
                            .get(getKeyByValue(tDistMap, findClosestNumber(listValues, avgSumDist)));
                    clust.setCentroid(newCentroid);
                }

            }

        }
        // create an iterator
        Iterator iterator = clusterSet.iterator();

        // check values
        while (iterator.hasNext()) {

            Cluster c = (Cluster) iterator.next();
            bw.write(c.getId() + "\t");
            System.out.print(c.getId() + "\t");

            for (Tweet t : c.getMembers()) {
                bw.write(t.getTweetID() + ", ");
                System.out.print(t.getTweetID() + ",");

            }
            bw.write("\n");
            System.out.println("");
        }

        System.out.println("");

        System.out.println("SSE " + sumSquaredErrror(clusterSet));

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        bw.close();
        fw.close();
    }
}

From source file:org.apache.ambari.server.api.services.serializers.CsvSerializerTest.java

@Test
public void testSerializeResources_NoColumnInfo() throws Exception {
    Result result = new ResultImpl(true);
    result.setResultStatus(new ResultStatus(ResultStatus.STATUS.OK));
    TreeNode<Resource> tree = result.getResultTree();

    List<TreeMap<String, Object>> data = new ArrayList<TreeMap<String, Object>>() {
        {/*  w  w w. j av a 2s  . c o m*/
            add(new TreeMap<String, Object>() {
                {
                    put("property1", "value1a");
                    put("property2", "value2a");
                    put("property3", "value3a");
                    put("property4", "value4a");
                }
            });
            add(new TreeMap<String, Object>() {
                {
                    put("property1", "value1'b");
                    put("property2", "value2'b");
                    put("property3", "value3'b");
                    put("property4", "value4'b");
                }
            });
            add(new TreeMap<String, Object>() {
                {
                    put("property1", "value1,c");
                    put("property2", "value2,c");
                    put("property3", "value3,c");
                    put("property4", "value4,c");
                }
            });
        }
    };

    tree.setName("items");
    tree.setProperty("isCollection", "true");

    addChildResource(tree, "resource", 0, data.get(0));
    addChildResource(tree, "resource", 1, data.get(1));
    addChildResource(tree, "resource", 2, data.get(2));

    replayAll();

    //execute test
    Object o = new CsvSerializer().serialize(result).toString().replace("\r", "");

    verifyAll();

    assertNotNull(o);

    StringReader reader = new StringReader(o.toString());
    CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
    List<CSVRecord> records = csvParser.getRecords();

    assertNotNull(records);
    assertEquals(3, records.size());

    int i = 0;
    for (CSVRecord record : records) {
        TreeMap<String, Object> actualData = data.get(i++);
        assertEquals(actualData.size(), record.size());

        for (String item : record) {
            assertTrue(actualData.containsValue(item));
        }
    }

    csvParser.close();
}

From source file:nz.co.fortytwo.signalk.server.RouteManager.java

private void reloadCharts() {
    String staticDir = Util.getConfigProperty(STATIC_DIR);
    if (!staticDir.endsWith("/")) {
        staticDir = staticDir + "/";
    }//from   ww  w. j a  v a 2  s  .c  om
    File mapDir = new File(staticDir + Util.getConfigProperty(MAP_DIR));
    logger.debug("Reloading charts from: " + mapDir.getAbsolutePath());
    if (mapDir == null || !mapDir.exists() || mapDir.listFiles() == null)
        return;
    UploadProcessor processor = new UploadProcessor();
    TreeMap<String, Object> treeMap = new TreeMap<String, Object>(signalkModel.getSubMap("resources.charts"));
    for (File chart : mapDir.listFiles()) {
        if (chart.isDirectory()) {
            if (treeMap.containsValue(chart.getName())) {
                logger.info("chart " + chart.getName() + " already in model");
            } else {
                logger.debug("Reloading: " + chart.getName());
                try {
                    processor.loadChart(chart.getName());
                } catch (Exception e) {
                    logger.warn(e.getMessage());
                }
            }
        }
    }

}

From source file:org.opencms.workplace.tools.content.CmsElementRename.java

/**
 * Returns a retained list of xml pages that belongs to the specified template.<p>
 * //from   ww w  .  j  a  va 2 s .  c  o m
 * @param xmlPages a list of all xml pages 
 * @return a retained list of xml pages that belongs to the specified template
 */
private List getRetainedPagesWithTemplate(List xmlPages) {

    // list of resources belongs to the selected template
    List resourcesWithTemplate = new ArrayList();
    TreeMap templates = null;
    try {
        templates = CmsNewResourceXmlPage.getTemplates(getCms(), null);
    } catch (CmsException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
    // check if the users selected template is valid. 
    if ((templates != null) && templates.containsValue(getParamTemplate())) {
        // iterate the xmlPages list and add all resources with the specified template to the resourcesWithTemplate list
        Iterator i = xmlPages.iterator();
        while (i.hasNext()) {
            CmsResource currentPage = (CmsResource) i.next();
            // read the template property
            CmsProperty templateProperty;
            try {
                templateProperty = getCms().readPropertyObject(getCms().getSitePath(currentPage),
                        CmsPropertyDefinition.PROPERTY_TEMPLATE, false);
            } catch (CmsException e2) {
                if (LOG.isErrorEnabled()) {
                    LOG.error(e2);
                }
                continue;
            }
            // add currentResource if the template property value is the same as the given template
            if (getParamTemplate().equals(templateProperty.getValue())) {
                resourcesWithTemplate.add(currentPage);
            }
        }
        // retain the list of pages against the list with template 
        xmlPages.retainAll(resourcesWithTemplate);
    }

    return xmlPages;
}

From source file:de.uzk.hki.da.sb.SIPFactory.java

private Feedback checkMetadataForLicense(int jobId, File sourceFolder, File packageFolder) {
    boolean premisLicenseBool = contractRights.getCclincense() != null;
    boolean metsLicenseBool = false;
    boolean lidoLicenseBool = false;
    boolean publicationBool = contractRights.getPublicRights().getAllowPublication();

    TreeMap<File, String> metadataFileWithType;
    try {/*w w w. j  ava2 s . c om*/
        metadataFileWithType = new FormatDetectionService(sourceFolder).getMetadataFileWithType();

        if (metadataFileWithType.containsValue(C.CB_PACKAGETYPE_METS)) {
            ArrayList<File> metsFiles = new ArrayList<File>();

            ArrayList<MetsLicense> licenseMetsFile = new ArrayList<MetsLicense>();
            for (File f : metadataFileWithType.keySet())
                if (metadataFileWithType.get(f).equals(C.CB_PACKAGETYPE_METS))
                    metsFiles.add(f);
            for (File f : metsFiles) {// assuming more as usual mets is allowed (check is done by FormatDetectionService) e.g. publicMets for testcase-creation
                SAXBuilder builder = XMLUtils.createNonvalidatingSaxBuilder();
                Document metsDoc = builder.build(f);
                MetsParser mp = new MetsParser(metsDoc);
                licenseMetsFile.add(mp.getLicenseForWholeMets());
            }
            Collections.sort(licenseMetsFile, new NullLastComparator<MetsLicense>());
            if (licenseMetsFile.get(0) == null) // all licenses are null
                metsLicenseBool = false;
            else if (!licenseMetsFile.get(0).equals(licenseMetsFile.get(licenseMetsFile.size() - 1))) // first and last lic have to be same in sorted array
                return Feedback.INVALID_LICENSE_DATA_IN_METADATA;
            else
                metsLicenseBool = true;
        } else if (metadataFileWithType.containsValue(C.CB_PACKAGETYPE_LIDO)) {
            ArrayList<File> lidoFiles = new ArrayList<File>();

            ArrayList<LidoLicense> licenseLidoFile = new ArrayList<LidoLicense>();
            for (File f : metadataFileWithType.keySet())
                if (metadataFileWithType.get(f).equals(C.CB_PACKAGETYPE_LIDO))
                    lidoFiles.add(f);
            for (File f : lidoFiles) {// assuming more as one metadata is allowed (check is done by FormatDetectionService) 
                SAXBuilder builder = XMLUtils.createNonvalidatingSaxBuilder();
                Document metsDoc = builder.build(f);
                LidoParser lp = new LidoParser(metsDoc);
                licenseLidoFile.add(lp.getLicenseForWholeLido());
            }
            Collections.sort(licenseLidoFile, new NullLastComparator<LidoLicense>());
            if (licenseLidoFile.get(0) == null) // all licenses are null
                lidoLicenseBool = false;
            else if (!licenseLidoFile.get(0).equals(licenseLidoFile.get(licenseLidoFile.size() - 1))) // first and last lic have to be same in sorted array
                return Feedback.INVALID_LICENSE_DATA_IN_METADATA;
            else
                lidoLicenseBool = true;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return Feedback.INVALID_LICENSE_DATA_IN_METADATA;
    }
    //activate to be able to create non licensed test sips
    //publicationBool=false;
    //premisLicenseBool=false;
    //publicationBool=false;
    if (premisLicenseBool && (metsLicenseBool || lidoLicenseBool)) {
        return Feedback.DUPLICATE_LICENSE_DATA;
    }

    if (publicationBool && !premisLicenseBool && !metsLicenseBool && !lidoLicenseBool) {
        return Feedback.PUBLICATION_NO_LICENSE;
    }

    logger.info(
            "License is satisfiable: Premis-License:" + premisLicenseBool + " Mets-License:" + metsLicenseBool
                    + " Lido-License:" + lidoLicenseBool + " Publication-Decision:" + publicationBool);

    return Feedback.SUCCESS;
}