Example usage for java.util SortedMap values

List of usage examples for java.util SortedMap values

Introduction

In this page you can find the example usage for java.util SortedMap values.

Prototype

Collection<V> values();

Source Link

Document

Returns a Collection view of the values contained in this map.

Usage

From source file:Main.java

public static void main(String[] args) {
    SortedMap<String, Integer> sortedMap = new TreeMap<String, Integer>();
    sortedMap.put("A", 1);
    sortedMap.put("B", 2);
    sortedMap.put("C", 3);
    sortedMap.put("D", 4);
    sortedMap.put("E", 5);
    sortedMap.put("java2s", 6);

    System.out.println(sortedMap.values());

}

From source file:CollectionAll.java

public static void main(String[] args) {
    List list1 = new LinkedList();
    list1.add("list");
    list1.add("dup");
    list1.add("x");
    list1.add("dup");
    traverse(list1);/*  w w w  .  ja va  2  s  .c om*/
    List list2 = new ArrayList();
    list2.add("list");
    list2.add("dup");
    list2.add("x");
    list2.add("dup");
    traverse(list2);
    Set set1 = new HashSet();
    set1.add("set");
    set1.add("dup");
    set1.add("x");
    set1.add("dup");
    traverse(set1);
    SortedSet set2 = new TreeSet();
    set2.add("set");
    set2.add("dup");
    set2.add("x");
    set2.add("dup");
    traverse(set2);
    LinkedHashSet set3 = new LinkedHashSet();
    set3.add("set");
    set3.add("dup");
    set3.add("x");
    set3.add("dup");
    traverse(set3);
    Map m1 = new HashMap();
    m1.put("map", "Java2s");
    m1.put("dup", "Kava2s");
    m1.put("x", "Mava2s");
    m1.put("dup", "Lava2s");
    traverse(m1.keySet());
    traverse(m1.values());
    SortedMap m2 = new TreeMap();
    m2.put("map", "Java2s");
    m2.put("dup", "Kava2s");
    m2.put("x", "Mava2s");
    m2.put("dup", "Lava2s");
    traverse(m2.keySet());
    traverse(m2.values());
    LinkedHashMap /* from String to String */ m3 = new LinkedHashMap();
    m3.put("map", "Java2s");
    m3.put("dup", "Kava2s");
    m3.put("x", "Mava2s");
    m3.put("dup", "Lava2s");
    traverse(m3.keySet());
    traverse(m3.values());
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5bAgreementMeasures.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    String inputDir = args[0];//ww  w.j  ava 2s . c  o  m

    // all annotations
    List<AnnotatedArgumentPair> allArgumentPairs = new ArrayList<>();

    Collection<File> files = IOHelper.listXmlFiles(new File(inputDir));

    for (File file : files) {
        allArgumentPairs.addAll((List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file));
    }

    // for collecting the rank of n-th best worker per HIT
    SortedMap<Integer, DescriptiveStatistics> nThWorkerOnHITRank = new TreeMap<>();
    // confusion matrix wrt. gold data for each n-th best worker on HIT
    SortedMap<Integer, ConfusionMatrix> nThWorkerOnHITConfusionMatrix = new TreeMap<>();

    // initialize maps
    for (int i = 0; i < TOP_K_VOTES; i++) {
        nThWorkerOnHITRank.put(i, new DescriptiveStatistics());
        nThWorkerOnHITConfusionMatrix.put(i, new ConfusionMatrix());
    }

    for (AnnotatedArgumentPair argumentPair : allArgumentPairs) {
        // sort turker rank and their vote
        SortedMap<Integer, String> rankAndVote = new TreeMap<>();

        System.out.println(argumentPair.mTurkAssignments.size());

        for (AnnotatedArgumentPair.MTurkAssignment assignment : argumentPair.mTurkAssignments) {
            rankAndVote.put(assignment.getTurkRank(), assignment.getValue());
        }

        String goldLabel = argumentPair.getGoldLabel();

        System.out.println(rankAndVote);

        // top K workers for the HIT
        List<String> topKVotes = new ArrayList<>(rankAndVote.values()).subList(0, TOP_K_VOTES);

        // rank of top K workers
        List<Integer> topKRanks = new ArrayList<>(rankAndVote.keySet()).subList(0, TOP_K_VOTES);

        System.out.println("Top K votes: " + topKVotes);
        System.out.println("Top K ranks: " + topKRanks);

        // extract only category (a1, a2, or equal)
        List<String> topKVotesOnlyCategory = new ArrayList<>();
        for (String vote : topKVotes) {
            String category = vote.split("_")[2];
            topKVotesOnlyCategory.add(category);
        }

        System.out.println("Top " + TOP_K_VOTES + " workers' decisions: " + topKVotesOnlyCategory);

        if (goldLabel == null) {
            System.out.println("No gold label estimate for " + argumentPair.getId());
        } else {
            // update statistics
            for (int i = 0; i < TOP_K_VOTES; i++) {
                nThWorkerOnHITConfusionMatrix.get(i).increaseValue(goldLabel, topKVotesOnlyCategory.get(i));

                // rank is +1 (we don't start ranking from zero)
                nThWorkerOnHITRank.get(i).addValue(topKRanks.get(i) + 1);
            }
        }
    }

    for (int i = 0; i < TOP_K_VOTES; i++) {
        System.out.println("n-th worker : " + (i + 1) + " -----------");
        System.out.println(nThWorkerOnHITConfusionMatrix.get(i).printNiceResults());
        System.out.println(nThWorkerOnHITConfusionMatrix.get(i));
        System.out.println("Average rank: " + nThWorkerOnHITRank.get(i).getMean() + ", stddev "
                + nThWorkerOnHITRank.get(i).getStandardDeviation());
    }

}

From source file:Main.java

public static Collection<Object> getSortedValues(Map<Integer, Object> vParameters) {
    if (vParameters == null || vParameters.size() == 0)
        return null;
    Set<Integer> keys = vParameters.keySet();

    SortedMap<Integer, Object> sortedMap = new TreeMap<Integer, Object>(vParameters);
    Collection<Object> result = sortedMap.values();
    return result;
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T, U> U[] getSortedValueArray(SortedMap<T, U> m, Class<U> clazz) {
    if (m == null || m.size() == 0) {
        U[] a = (U[]) java.lang.reflect.Array.newInstance(clazz, 0);
        return Collections.<U>emptyList().toArray(a);
    } else {//  www  .  j a  v a  2s  . c o m
        U[] a = (U[]) java.lang.reflect.Array.newInstance(clazz, m.size());
        return m.values().toArray(a);
    }
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step9AgreementCollector.java

@SuppressWarnings("unchecked")
public static void computeObservedAgreement(File goldDataFolder, File outputDir) throws Exception {
    // iterate over query containers
    for (File f : FileUtils.listFiles(goldDataFolder, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));

        for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) {

            // only non-empty and annotated results
            // No annotations found for document: clueWebID: clueweb12-1407wb-22-10643, queryID: 1006
            // <clueWebID>clueweb12-1407wb-22-10643</clueWebID>
            // <score>5.93809186</score>
            // <additionalInfo>indri</additionalInfo>
            // <plainText></plainText>

            if (rankedResult.plainText != null && !rankedResult.plainText.isEmpty()) {
                if (rankedResult.mTurkRelevanceVotes.isEmpty()) {
                    //                        throw new IllegalStateException("No annotations found for document: "
                    System.err.println("No annotations found for document: " + "clueWebID: "
                            + rankedResult.clueWebID + ", queryID: " + queryResultContainer.qID);
                } else {

                    // first, get all the sentence IDs
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));

                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    // for each sentence, we'll collect all its annotations
                    TreeMap<Integer, SortedMap<String, String>> sentencesAndRelevanceAnnotations = collectSentenceIDs(
                            jCas);//w  w  w.j  a v a  2  s.  co  m

                    // now we will the map with mturk annotations
                    // the list of true/false for each sentence will be consistent (the annotator ordering remains)
                    for (QueryResultContainer.MTurkRelevanceVote mTurkRelevanceVote : rankedResult.mTurkRelevanceVotes) {
                        for (QueryResultContainer.SingleSentenceRelevanceVote sentenceRelevanceVote : mTurkRelevanceVote.singleSentenceRelevanceVotes) {

                            String sentenceIDString = sentenceRelevanceVote.sentenceID;
                            if (sentenceIDString == null || sentenceIDString.isEmpty()) {
                                throw new IllegalStateException("Empty sentence ID for turker "
                                        + mTurkRelevanceVote.turkID + ", HIT: " + mTurkRelevanceVote.hitID
                                        + ", clueWebID: " + rankedResult.clueWebID + ", queryID: "
                                        + queryResultContainer.qID);
                            } else {

                                Integer sentenceIDInt = Integer.valueOf(sentenceIDString);
                                String value = sentenceRelevanceVote.relevant;

                                // add to the list

                                // sanity check first
                                if (sentencesAndRelevanceAnnotations.get(sentenceIDInt)
                                        .containsKey(mTurkRelevanceVote.turkID)) {
                                    System.err.println("Annotations for sentence " + sentenceIDInt
                                            + " for turker " + mTurkRelevanceVote.turkID + " are duplicate");
                                }

                                sentencesAndRelevanceAnnotations.get(sentenceIDInt)
                                        .put(mTurkRelevanceVote.turkID, value);
                            }
                        }
                    }

                    //                    for (Map.Entry<Integer, SortedMap<String, String>> entry : sentencesAndRelevanceAnnotations
                    //                            .entrySet()) {
                    //                        System.out.println(entry.getKey() + ": " + entry.getValue());
                    //                    }

                    // we collect only the "clean" ones
                    Map<Integer, SortedMap<String, String>> cleanSentencesAndRelevanceAnnotations = new HashMap<>();

                    // sanity check -- all sentences are covered with the same number of annotations
                    for (Map.Entry<Integer, SortedMap<String, String>> entry : sentencesAndRelevanceAnnotations
                            .entrySet()) {
                        SortedMap<String, String> singleSentenceAnnotations = entry.getValue();

                        // remove empty sentences
                        if (singleSentenceAnnotations.values().isEmpty()) {
                            //                                throw new IllegalStateException(
                            System.err.println("Empty annotations for sentence, " + "sentenceID: "
                                    + entry.getKey() + ", " + "clueWebID: " + rankedResult.clueWebID
                                    + ", queryID: " + queryResultContainer.qID + "; number of assignments: "
                                    + singleSentenceAnnotations.values().size() + ", expected: "
                                    + NUMBER_OF_TURKERS_PER_HIT + ". Sentence will be skipped in evaluation");
                        } else if (singleSentenceAnnotations.values().size() != NUMBER_OF_TURKERS_PER_HIT) {
                            System.err.println("Inconsistent annotations for sentences, " + "sentenceID: "
                                    + entry.getKey() + ", " + "clueWebID: " + rankedResult.clueWebID
                                    + ", queryID: " + queryResultContainer.qID + "; number of assignments: "
                                    + singleSentenceAnnotations.values().size() + ", expected: "
                                    + NUMBER_OF_TURKERS_PER_HIT + ". Sentence will be skipped in evaluation");
                        } else {
                            cleanSentencesAndRelevanceAnnotations.put(entry.getKey(), entry.getValue());
                        }
                    }

                    // fill the annotation study

                    CodingAnnotationStudy study = new CodingAnnotationStudy(NUMBER_OF_TURKERS_PER_HIT);
                    study.addCategory("true");
                    study.addCategory("false");

                    for (SortedMap<String, String> singleSentenceAnnotations : cleanSentencesAndRelevanceAnnotations
                            .values()) {
                        // only non-empty sentences
                        Collection<String> values = singleSentenceAnnotations.values();
                        if (!values.isEmpty() && values.size() == NUMBER_OF_TURKERS_PER_HIT) {
                            study.addItemAsArray(values.toArray());
                        }

                    }

                    //                    System.out.println(study.getCategories());

                    // Fleiss' multi-pi.
                    FleissKappaAgreement fleissKappaAgreement = new FleissKappaAgreement(study);

                    double percentage;
                    try {
                        percentage = fleissKappaAgreement.calculateObservedAgreement();
                    } catch (InsufficientDataException ex) {
                        // dkpro-statistics feature, see https://github.com/dkpro/dkpro-statistics/issues/24
                        percentage = 1.0;
                    }

                    if (!Double.isNaN(percentage)) {
                        rankedResult.observedAgreement = percentage;
                        //                        System.out.println(sentencesAndRelevanceAnnotations.values());
                    } else {
                        System.err.println("Observed agreement is NaN.");
                    }
                }
            }
        }

        // and save the query to output dir
        File outputFile = new File(outputDir, queryResultContainer.qID + ".xml");
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcMultiRowRecordWriter.java

private static PreparedStatement generatePreparedStatement(SortedMap<String, String> columns, int numRecords,
        Object tableName, Connection connection) throws SQLException {
    String valuePlaceholder = String.format("(%s)", Joiner.on(", ").join(columns.values()));
    String valuePlaceholders = StringUtils.repeat(valuePlaceholder, ", ", numRecords);
    String query = String.format("INSERT INTO %s (%s) VALUES %s", tableName,
            // keySet and values will both return the same ordering, due to using a SortedMap
            Joiner.on(", ").join(columns.keySet()), valuePlaceholders);

    return connection.prepareStatement(query);
}

From source file:io.lavagna.model.ProjectMetadata.java

private static String hash(SortedMap<Integer, CardLabel> labels,
        SortedMap<Integer, LabelListValueWithMetadata> labelListValues,
        Map<ColumnDefinition, BoardColumnDefinition> columnsDefinition) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream daos = new DataOutputStream(baos);

    try {/*from  www.  j a va 2s . c  om*/

        for (CardLabel cl : labels.values()) {
            hash(daos, cl);
        }

        for (LabelListValueWithMetadata l : labelListValues.values()) {
            hash(daos, l);
        }

        for (BoardColumnDefinition b : columnsDefinition.values()) {
            hash(daos, b);
        }

        daos.flush();
        return DigestUtils.sha256Hex(new ByteArrayInputStream(baos.toByteArray()));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.shept.util.FileUtils.java

/**
 * Compare the source path and the destination path for filenames with the filePattern
 * e.g. *.bak, *tmp and copy these files to the destination dir if they are not present at the
 * destination or if they have changed (by modifactionDate)
 * /*from  w w w  . j av a  2 s .  com*/
 * @param destPath
 * @param sourcePath
 * @param filePattern
 * @return the number of files being copied
 */
public static Integer syncAdd(String sourcePath, String destPath, String filePattern) {
    // check for new files since the last check which need to be copied
    Integer number = 0;
    SortedMap<FileNameDate, File> destMap = fileMapByNameAndDate(destPath, filePattern);
    SortedMap<FileNameDate, File> sourceMap = fileMapByNameAndDate(sourcePath, filePattern);
    // identify the list of source files different from their destinations
    for (FileNameDate fk : destMap.keySet()) {
        sourceMap.remove(fk);
    }

    // copy the list of files from source to destination
    for (File file : sourceMap.values()) {
        log.debug(file.getName() + ": " + new Date(file.lastModified()));
        File copy = new File(destPath, file.getName());
        try {
            if (!copy.exists()) {
                // copy to tmp file first to avoid clashes during lengthy copy action
                File tmp = File.createTempFile("vrs", ".tmp", copy.getParentFile());
                FileCopyUtils.copy(file, tmp);
                if (!tmp.renameTo(copy)) {
                    tmp.delete(); // cleanup if we fail
                }
                number++;
            }
        } catch (IOException ex) {
            log.error("FileCopy error for file " + file.getName(), ex);
        }
    }
    return number;
}

From source file:com.oltpbenchmark.util.CollectionUtil.java

/**
 * //from w w w. j a  va 2  s.  c o m
 * @param <K>
 * @param <V>
 * @param map
 * @return
 */
public static <K extends Comparable<?>, V> List<V> getSortedList(SortedMap<K, Collection<V>> map) {
    List<V> ret = new ArrayList<V>();
    for (Collection<V> col : map.values()) {
        ret.addAll(col);
    } // FOR
    return (ret);
}