Example usage for java.util SortedSet toArray

List of usage examples for java.util SortedSet toArray

Introduction

In this page you can find the example usage for java.util SortedSet toArray.

Prototype

<T> T[] toArray(T[] a);

Source Link

Document

Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    SortedSet<String> set = new TreeSet<String>();
    set.add("b");
    set.add("c");
    set.add("a");

    Iterator it = set.iterator();
    while (it.hasNext()) {
        Object element = it.next();
    }// w ww  .ja v a2s  .  co m
    String[] array = (String[]) set.toArray(new String[set.size()]);
}

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

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // /home/user-ukp/research/data/dip/wp1-documents/step4-boiler-plate/
    File inputDir = new File(args[0] + "/");

    // MTurk result file

    // output dir
    File outputDir = new File(args[2]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();/*from w  w  w .j av a  2  s  . co  m*/

    }

    // Folder with success files
    File mturkSuccessDir = new File(args[1]);

    Collection<File> files = FileUtils.listFiles(mturkSuccessDir, new String[] { "result" }, false);
    if (files.isEmpty()) {
        throw new IllegalArgumentException("Input folder is empty. " + mturkSuccessDir);
    }

    HashMap<String, List<MTurkAnnotation>> mturkAnnotations = new HashMap<>();

    // parsing all CSV files
    for (File mturkCSVResultFile : files) {
        System.out.println("Parsing " + mturkCSVResultFile.getName());

        MTurkOutputReader outputReader = new MTurkOutputReader(
                new HashSet<>(Arrays.asList("annotation", "workerid")), mturkCSVResultFile);

        // for fixing broken data input: for each hit, collect all sentence IDs
        Map<String, SortedSet<String>> hitSentences = new HashMap<>();

        // first iteration: collect the sentences
        for (Map<String, String> record : outputReader) {
            String hitID = record.get("hitid");
            if (!hitSentences.containsKey(hitID)) {
                hitSentences.put(hitID, new TreeSet<>());
            }

            String relevantSentences = record.get("Answer.relevant_sentences");
            String irrelevantSentences = record.get("Answer.irrelevant_sentences");

            if (relevantSentences != null) {
                hitSentences.get(hitID).addAll(Arrays.asList(relevantSentences.split(",")));
            }

            if (irrelevantSentences != null) {
                hitSentences.get(hitID).addAll(Arrays.asList(irrelevantSentences.split(",")));
            }
        }

        // and now second iteration
        for (Map<String, String> record : outputReader) {
            String hitID = record.get("hitid");
            String annotatorID = record.get("workerid");
            String acceptTime = record.get("assignmentaccepttime");
            String submitTime = record.get("assignmentsubmittime");
            String relevantSentences = record.get("Answer.relevant_sentences");
            String irrelevantSentences = record.get("Answer.irrelevant_sentences");
            String reject = record.get("reject");
            String filename[];
            String comment;
            String clueWeb;
            String[] relevant = {};
            String[] irrelevant = {};

            filename = record.get("annotation").split("_");
            String fileXml = filename[0];
            clueWeb = filename[1].trim();
            comment = record.get("Answer.comment");

            if (relevantSentences != null) {
                relevant = relevantSentences.split(",");
            }

            if (irrelevantSentences != null) {
                irrelevant = irrelevantSentences.split(",");
            }

            // sanitizing data: if both relevant and irrelevant are empty, that's a bug
            // we're gonna look up all sentences from this HIT and treat this assignment
            // as if there were only irrelevant ones
            if (relevant.length == 0 && irrelevant.length == 0) {
                SortedSet<String> strings = hitSentences.get(hitID);
                irrelevant = new String[strings.size()];
                strings.toArray(irrelevant);
            }

            if (reject != null) {
                System.out.println(" HIT " + hitID + " annotated by " + annotatorID + " was rejected ");
            } else {
                /*
                // relevant sentences is a comma-delimited string,
                // this regular expression is rather strange
                // it must contain digits, it might be that there is only one space or a comma or some other char
                // digits are the sentence ids. if relevant sentences do not contain digits then it is wrong
                if (relevantSentences.matches("^\\D*$") &&
                    irrelevantSentences.matches("^\\D*$")) {
                try {
                    throw new IllegalStateException(
                            "No annotations found for HIT " + hitID + " in " +
                                    fileXml + " for document " + clueWeb);
                }
                catch (IllegalStateException ex) {
                    ex.printStackTrace();
                }
                        
                }
                */
                MTurkAnnotation mturkAnnotation;
                try {
                    mturkAnnotation = new MTurkAnnotation(hitID, annotatorID, acceptTime, submitTime, comment,
                            clueWeb, relevant, irrelevant);
                } catch (IllegalArgumentException ex) {
                    throw new IllegalArgumentException("Record: " + record, ex);
                }

                List<MTurkAnnotation> listOfAnnotations = mturkAnnotations.get(fileXml);

                if (listOfAnnotations == null) {
                    listOfAnnotations = new ArrayList<>();
                }
                listOfAnnotations.add(mturkAnnotation);
                mturkAnnotations.put(fileXml, listOfAnnotations);
            }

        }
        //            parser.close();
    }

    // Debugging: output number of HITs of a query
    System.out.println("Accepted HITs for a query:");
    for (Map.Entry e : mturkAnnotations.entrySet()) {
        ArrayList<MTurkAnnotation> a = (ArrayList<MTurkAnnotation>) e.getValue();
        System.out.println(e.getKey() + " " + a.size());
    }

    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        String fileName = f.getName();
        List<MTurkAnnotation> listOfAnnotations = mturkAnnotations.get(fileName);

        if (listOfAnnotations == null || listOfAnnotations.isEmpty()) {
            throw new IllegalStateException("No annotations for " + f.getName());
        }

        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            for (MTurkAnnotation mtAnnotation : listOfAnnotations) {
                String clueWeb = mtAnnotation.clueWeb;
                if (rankedResults.clueWebID.equals(clueWeb)) {
                    List<QueryResultContainer.MTurkRelevanceVote> mTurkRelevanceVotes = rankedResults.mTurkRelevanceVotes;
                    QueryResultContainer.MTurkRelevanceVote relevanceVote = new QueryResultContainer.MTurkRelevanceVote();
                    String annotatorID = mtAnnotation.annotatorID;
                    String hitID = mtAnnotation.hitID;
                    String acceptTime = mtAnnotation.acceptTime;
                    String submitTime = mtAnnotation.submitTime;
                    String comment = mtAnnotation.comment;
                    String[] relevant = mtAnnotation.relevant;
                    String[] irrelevant = mtAnnotation.irrelevant;
                    relevanceVote.turkID = annotatorID.trim();
                    relevanceVote.hitID = hitID.trim();
                    relevanceVote.acceptTime = acceptTime.trim();
                    relevanceVote.submitTime = submitTime.trim();
                    relevanceVote.comment = comment != null ? comment.trim() : null;
                    if (relevant.length == 0 && irrelevant.length == 0) {
                        try {
                            throw new IllegalStateException("the length of the annotations is 0"
                                    + rankedResults.clueWebID + " for HIT " + relevanceVote.hitID);
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        }
                    }
                    for (String r : relevant) {
                        String sentenceId = r.trim();
                        if (!sentenceId.isEmpty() && sentenceId.matches("\\d+")) {
                            QueryResultContainer.SingleSentenceRelevanceVote singleSentenceVote = new QueryResultContainer.SingleSentenceRelevanceVote();
                            singleSentenceVote.sentenceID = sentenceId;
                            singleSentenceVote.relevant = "true";
                            relevanceVote.singleSentenceRelevanceVotes.add(singleSentenceVote);
                        }
                    }
                    for (String r : irrelevant) {
                        String sentenceId = r.trim();
                        if (!sentenceId.isEmpty() && sentenceId.matches("\\d+")) {
                            QueryResultContainer.SingleSentenceRelevanceVote singleSentenceVote = new QueryResultContainer.SingleSentenceRelevanceVote();
                            singleSentenceVote.sentenceID = sentenceId;
                            singleSentenceVote.relevant = "false";
                            relevanceVote.singleSentenceRelevanceVotes.add(singleSentenceVote);
                        }
                    }
                    mTurkRelevanceVotes.add(relevanceVote);
                }
            }

        }
        File outputFile = new File(outputDir, f.getName());
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }

}

From source file:com.asakusafw.runtime.stage.input.StageInputDriver.java

private static String[] buildDictionary(List<StageInput> inputList) {
    assert inputList != null;
    SortedSet<String> values = new TreeSet<>();
    for (StageInput input : inputList) {
        values.add(input.getPathString());
        values.add(input.getFormatClass().getName());
        values.add(input.getMapperClass().getName());
        values.addAll(input.getAttributes().keySet());
        values.addAll(input.getAttributes().values());
    }/*from   ww  w  .ja va2 s. c  om*/
    return values.toArray(new String[values.size()]);
}

From source file:eu.itesla_project.modules.histo.IIDM2DB.java

public static JSONArray toTopoSet(VoltageLevel vl) throws JSONException {
    SortedMap<String, JSONArray> topoList = new TreeMap<>();

    Multimap<String, String> topoTmp = HashMultimap.create();

    vl.visitEquipments(new TerminalTopologyVisitor() {
        @Override/*from ww w . java2  s .c o m*/
        public void visitTerminal(Terminal t) {
            Connectable c = t.getConnectable();
            Bus b = t.getBusView().getBus();
            if (b == null) {
                if (c.getType() == ConnectableType.LOAD || c.getType() == ConnectableType.GENERATOR
                        || c.getType() == ConnectableType.SHUNT_COMPENSATOR) {
                    // add the injection in the topo set even if not connected but just connectable to this bus
                    // see WP4.2 data mining topology spec for more detailed information
                    b = t.getBusView().getConnectableBus();
                }
            }
            if (b != null) {
                topoTmp.put(b.getId(), c.getId());
            } else {
                // connect the equipment to its own bus
                topoTmp.put(c.getId() + "FICTIVE_BUS", c.getId());
            }
        }
    });

    for (Map.Entry<String, Collection<String>> entry : topoTmp.asMap().entrySet()) {
        SortedSet<String> topoContent = new TreeSet<>(entry.getValue());
        JSONArray topoArray = new JSONArray(topoContent.toArray(new String[] {}));
        topoList.put(topoArray.toString(), topoArray);
    }

    return new JSONArray(topoList.values().toArray(new JSONArray[] {}));
}

From source file:org.codecyprus.android_client.sync.JsonParser.java

public static Category[] parseGetActiveCategories(final String json) throws JSONException, JsonParseException {
    final Category[] categories = parseGetCategories(json);

    // filter out finished competitions
    final SortedSet<Category> activeCategories = new TreeSet<>();
    final long now = System.currentTimeMillis();
    for (final Category category : categories) {
        try {/*  w w  w .  j a  va2s.  c  o  m*/
            final Date validUntil = CategoriesAdapter.SIMPLE_DATE_FORMAT.parse(category.getValidUntil());
            if (now < validUntil.getTime()) {
                activeCategories.add(category);
            }
        } catch (ParseException pe) {
            Log.e(TAG, pe.getMessage());
        }
    }
    return activeCategories.toArray(new Category[activeCategories.size()]);
}

From source file:com.dowdandassociates.gentoo.bootstrap.LatestImageProvider.java

@Override
public Optional<Image> get() {
    DescribeImagesResult result = ec2Client.describeImages(getRequest());

    Map<String, Image> imageMap = new HashMap<String, Image>();

    for (Image image : result.getImages()) {
        String imageLocation = StringUtils.substringAfterLast(image.getImageLocation(), "/");
        if (StringUtils.isBlank(imageLocation)) {
            imageLocation = image.getImageLocation();
        }//from  ww w.  j a v  a 2  s .  c  o  m
        log.info("imageLocation = " + imageLocation);
        imageMap.put(imageLocation, image);
    }

    if (imageMap.isEmpty()) {
        return Optional.absent();
    }

    SortedSet<String> sortedKeySet = new TreeSet<String>();
    sortedKeySet.addAll(imageMap.keySet());
    String[] keys = sortedKeySet.toArray(new String[0]);
    log.info("key = " + keys[keys.length - 1]);
    return Optional.fromNullable(imageMap.get(keys[keys.length - 1]));
}

From source file:org.alfresco.repo.admin.RepoServerMgmt.java

public String[] listUserNamesNonExpired() {
    return useManagedResourceClassloader(new Work<String[]>() {
        @Override//from  w w w  .j a  va 2 s .co  m
        String[] doWork() {
            Set<String> userSet = authenticationService.getUsersWithTickets(true);
            SortedSet<String> sorted = new TreeSet<String>(userSet);
            return sorted.toArray(new String[0]);
        }
    });
}

From source file:org.alfresco.repo.admin.RepoServerMgmt.java

public String[] listUserNamesAll() {
    return useManagedResourceClassloader(new Work<String[]>() {
        @Override//from   w  w w.j ava  2 s . c  o  m
        String[] doWork() {
            Set<String> userSet = authenticationService.getUsersWithTickets(false);
            SortedSet<String> sorted = new TreeSet<String>(userSet);
            return sorted.toArray(new String[0]);
        }
    });
}

From source file:fi.smaa.libror.PerformanceMatrix.java

private void initializeLevelIndices() {
    for (int i = 0; i < getNrCrit(); i++) {
        SortedSet<Double> s = new TreeSet<Double>();
        for (Double d : levels[i].toArray()) {
            s.add(d);/*w  w  w. ja  v  a  2s  .  c om*/
        }
        Double[] arr = s.toArray(new Double[0]);
        int[] colIndices = new int[getNrAlts()];
        for (int j = 0; j < getNrAlts(); j++) {
            for (int k = 0; k < arr.length; k++) {
                if (arr[k] == matrix.getEntry(j, i)) {
                    colIndices[j] = k;
                    break;
                }
            }
        }
        levelIndices.add(colIndices);
    }
}

From source file:uk.gov.phe.gis.thematics.classification.classifiers.precision.rounding.Generic.java

public double[] round(double[] values, double[] excludes) {
    SortedSet<Double> excludeSet = new TreeSet<Double>(Arrays.asList(ArrayUtils.toObject(excludes)));
    SortedSet<Double> breakSet = new TreeSet<Double>();

    for (double b : values) {
        double roundedBreak = round(b);
        if (excludeSet.contains(roundedBreak) == false) {
            breakSet.add(roundedBreak);/*from w  ww.  j  a v  a2 s.  c  om*/
        }
    }
    return ArrayUtils.toPrimitive(breakSet.toArray(new Double[breakSet.size()]));
}