Example usage for java.util Collections sort

List of usage examples for java.util Collections sort

Introduction

In this page you can find the example usage for java.util Collections sort.

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> void sort(List<T> list, Comparator<? super T> c) 

Source Link

Document

Sorts the specified list according to the order induced by the specified comparator.

Usage

From source file:Main.java

public static <T> int binarySearch(List<T> list, T target, Comparator<T> comparator) {
    Collections.sort(list, comparator);
    return Collections.binarySearch(list, target, comparator);
}

From source file:Main.java

public static <T> List<T> sort(Collection<T> collection, Comparator<T> comparator) {
    List<T> list = new ArrayList<T>(collection);
    Collections.sort(list, comparator);
    return list;//w w  w .j a  va  2  s.  com
}

From source file:Main.java

public static String prepareFilePathForVideoSaveWithDraftUri(Uri draftUri) {
    String draftPath = draftUri.getPath();
    String draftMediaDirPath = draftPath.substring(0, draftPath.length() - 5);
    File draftMediaDir = new File(draftMediaDirPath);
    if (!draftMediaDir.exists()) {
        draftMediaDir.mkdirs();// ww w  .  j a va2  s  .c o m
    }
    String[] files = draftMediaDir.list(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String filename) {
            return filename.endsWith("-0.mp4") || filename.endsWith("-a.mp4");
        }
    });
    List<String> filePaths = Arrays.asList(files);
    Collections.sort(filePaths, new Comparator<String>() {
        @Override
        public int compare(String lhs, String rhs) {
            return rhs.compareTo(lhs);
        }
    });
    if (filePaths.size() > 0) {
        for (String file : filePaths) {
            return new File(draftMediaDir, file.substring(0, file.length() - 6) + ".mp4").getAbsolutePath();
        }
    }
    return new File(draftMediaDir, generateRandomFilename("mp4")).getAbsolutePath();
}

From source file:Main.java

public static <T> Iterable<T> sort(Iterable<T> items, Comparator<T> comp) {
    List<T> list = Lists.newArrayList(items);
    Collections.sort(list, comp);
    return list;//from w  w w .j  a v a2 s  . co m
}

From source file:Main.java

/**
 * Returns the ordered keys of the given map
 * //from  w  w  w  .java 2s  .  co m
 * @param map
 *            the map
 * @return the ordered keys
 */
public final static List<String> getOrderedKeys(final Map<String, Object> map) {
    List<String> keys = new LinkedList<String>();
    if (!map.isEmpty()) {
        keys.addAll(map.keySet());
        Collections.sort(keys, new Comparator<String>() {
            /**
             * {@inheritDoc}
             */
            public int compare(String o1, String o2) {
                if (o1 == o2) {
                    return 0;
                }
                int n1 = -1;
                int n2 = -1;
                try {
                    n1 = Integer.parseInt(o1.substring(1));
                } catch (NumberFormatException e) {
                    // IGNORE
                }
                try {
                    n2 = Integer.parseInt(o2.substring(1));
                } catch (NumberFormatException e) {
                    // IGNORE
                }
                /*
                 * n1 is a number
                 */
                if (n1 != -1) {
                    /*
                     * n2 is a number
                     */
                    if (n2 != -1) {
                        return n1 - n2;
                    }
                    /*
                     * n2 is a string literal
                     */
                    return -1;
                }
                /*
                 * n1 is a literal and n2 is a number
                 */
                if (n2 != -1) {
                    return -1;
                }
                /*
                 * both are literals
                 */
                return o1.compareTo(o2);
            }
        });
    }
    return keys;
}

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

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    String inputDirWithArgumentPairs = args[0];

    File[] resultFiles;/*from   w  w w.j a v a  2  s  .co  m*/

    if (args[1].contains("*")) {
        File path = new File(args[1]);
        File directory = path.getParentFile();
        String regex = path.getName().replaceAll("\\*", "");

        List<File> files = new ArrayList<>(FileUtils.listFiles(directory, new String[] { regex }, false));
        resultFiles = new File[files.size()];
        for (int i = 0; i < files.size(); i++) {
            resultFiles[i] = files.get(i);
        }
    } else {
        // result file is a comma-separated list of CSV files from MTurk
        String[] split = args[1].split(",");
        resultFiles = new File[split.length];
        for (int i = 0; i < split.length; i++) {
            resultFiles[i] = new File(split[i]);
        }
    }

    File outputDir = new File(args[2]);

    if (!outputDir.exists()) {
        if (!outputDir.mkdirs()) {
            throw new IOException("Cannot create directory " + outputDir);
        }
    }

    // error if output folder not empty to prevent any confusion by mixing files
    if (!FileUtils.listFiles(outputDir, null, false).isEmpty()) {
        throw new IllegalArgumentException("Output dir " + outputDir + " is not empty");
    }

    // collected assignments with empty reason for rejections
    Set<String> assignmentsWithEmptyReason = new HashSet<>();

    // parse with first line as header
    MTurkOutputReader mTurkOutputReader = new MTurkOutputReader(resultFiles);

    Collection<File> files = FileUtils.listFiles(new File(inputDirWithArgumentPairs), new String[] { "xml" },
            false);

    if (files.isEmpty()) {
        throw new IOException("No xml files found in " + inputDirWithArgumentPairs);
    }

    // statistics: how many hits with how many assignments ; hit ID / assignments
    Map<String, Map<String, Integer>> assignmentsPerHits = new HashMap<>();

    // collect accept/reject statistics
    for (Map<String, String> record : mTurkOutputReader) {
        boolean wasRejected = "Rejected".equals(record.get("assignmentstatus"));
        String hitID = record.get("hitid");
        String hitTypeId = record.get("hittypeid");

        if (!wasRejected) {
            // update statistics
            if (!assignmentsPerHits.containsKey(hitTypeId)) {
                assignmentsPerHits.put(hitTypeId, new HashMap<String, Integer>());
            }

            if (!assignmentsPerHits.get(hitTypeId).containsKey(hitID)) {
                assignmentsPerHits.get(hitTypeId).put(hitID, 0);
            }

            assignmentsPerHits.get(hitTypeId).put(hitID, assignmentsPerHits.get(hitTypeId).get(hitID) + 1);
        }
    }

    // statistics: how many hits with how many assignments ; hit ID / assignments
    Map<String, Integer> approvedAssignmentsPerHit = new HashMap<>();
    Map<String, Integer> rejectedAssignmentsPerHit = new HashMap<>();

    // collect accept/reject statistics
    for (Map<String, String> record : mTurkOutputReader) {
        boolean approved = "Approved".equals(record.get("assignmentstatus"));
        boolean rejected = "Rejected".equals(record.get("assignmentstatus"));
        String hitID = record.get("hitid");

        if (approved) {
            // update statistics
            if (!approvedAssignmentsPerHit.containsKey(hitID)) {
                approvedAssignmentsPerHit.put(hitID, 0);
            }

            approvedAssignmentsPerHit.put(hitID, approvedAssignmentsPerHit.get(hitID) + 1);
        } else if (rejected) {
            // update statistics
            if (!rejectedAssignmentsPerHit.containsKey(hitID)) {
                rejectedAssignmentsPerHit.put(hitID, 0);
            }

            rejectedAssignmentsPerHit.put(hitID, rejectedAssignmentsPerHit.get(hitID) + 1);
        } else {
            throw new IllegalStateException(
                    "Unknown state: " + record.get("assignmentstatus") + " HITID: " + hitID);
        }
    }

    //        System.out.println("Approved: " + approvedAssignmentsPerHit);
    //        System.out.println("Rejected: " + rejectedAssignmentsPerHit);

    System.out.println("Approved (values): " + new HashSet<>(approvedAssignmentsPerHit.values()));
    System.out.println("Rejected (values): " + new HashSet<>(rejectedAssignmentsPerHit.values()));
    // rejection statistics
    int totalRejected = 0;
    for (Map.Entry<String, Integer> rejectionEntry : rejectedAssignmentsPerHit.entrySet()) {
        totalRejected += rejectionEntry.getValue();
    }

    System.out.println("Total rejections: " + totalRejected);

    /*
    // generate .success files for adding more annotations
    for (File resultFile : resultFiles) {
    String hitTypeID = mTurkOutputReader.getHitTypeIdForFile().get(resultFile);
            
    // assignments for that hittypeid (= file)
    Map<String, Integer> assignments = assignmentsPerHits.get(hitTypeID);
            
    prepareUpdateHITsFiles(assignments, hitTypeID, resultFile);
    }
    */

    int totalSavedPairs = 0;

    // load all previously prepared argument pairs
    for (File file : files) {
        List<ArgumentPair> argumentPairs = (List<ArgumentPair>) XStreamTools.getXStream().fromXML(file);

        List<AnnotatedArgumentPair> annotatedArgumentPairs = new ArrayList<>();

        for (ArgumentPair argumentPair : argumentPairs) {
            AnnotatedArgumentPair annotatedArgumentPair = new AnnotatedArgumentPair(argumentPair);

            // is there such an answer?
            String key = "Answer." + argumentPair.getId();

            // iterate only if there is such column to save time
            if (mTurkOutputReader.getColumnNames().contains(key)) {
                // now find the results
                for (Map<String, String> record : mTurkOutputReader) {
                    if (record.containsKey(key)) {
                        // extract the values
                        AnnotatedArgumentPair.MTurkAssignment assignment = new AnnotatedArgumentPair.MTurkAssignment();

                        boolean wasRejected = "Rejected".equals(record.get("assignmentstatus"));

                        // only non-rejected (if required)
                        if (!wasRejected) {
                            String hitID = record.get("hitid");
                            String workerID = record.get("workerid");
                            String assignmentId = record.get("assignmentid");
                            try {
                                assignment.setAssignmentAcceptTime(
                                        DATE_FORMAT.parse(record.get("assignmentaccepttime")));
                                assignment.setAssignmentSubmitTime(
                                        DATE_FORMAT.parse(record.get("assignmentsubmittime")));
                                assignment.setHitComment(record.get("Answer.feedback"));
                                assignment.setHitID(hitID);
                                assignment.setTurkID(workerID);
                                assignment.setAssignmentId(assignmentId);

                                // and answer specific fields
                                String valueRaw = record.get(key);

                                // so far the label has had format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal
                                // strip now only true label
                                String label = valueRaw.split("_")[2];

                                assignment.setValue(label);
                                String reason = record.get(key + "_reason");

                                // missing reason
                                if (reason == null) {
                                    assignmentsWithEmptyReason.add(assignmentId);
                                } else {
                                    assignment.setReason(reason);

                                    // get worker's stance
                                    String stanceRaw = record.get(key + "_stance");
                                    if (stanceRaw != null) {
                                        // parse stance
                                        String stance = stanceRaw.split("_stance_")[1];
                                        assignment.setWorkerStance(stance);
                                    }

                                    // we take maximal 5 assignments
                                    Collections.sort(annotatedArgumentPair.mTurkAssignments,
                                            new Comparator<AnnotatedArgumentPair.MTurkAssignment>() {
                                                @Override
                                                public int compare(AnnotatedArgumentPair.MTurkAssignment o1,
                                                        AnnotatedArgumentPair.MTurkAssignment o2) {
                                                    return o1.getAssignmentAcceptTime()
                                                            .compareTo(o2.getAssignmentAcceptTime());
                                                }
                                            });

                                    if (annotatedArgumentPair.mTurkAssignments
                                            .size() < MAXIMUM_ASSIGNMENTS_PER_HIT) {
                                        annotatedArgumentPair.mTurkAssignments.add(assignment);
                                    }
                                }
                            } catch (IllegalArgumentException | NullPointerException ex) {
                                System.err.println("Malformed annotations for HIT " + hitID + ", worker "
                                        + workerID + ", assignment " + assignmentId + "; " + ex.getMessage()
                                        + ", full record: " + record);
                            }
                        }
                    }
                }
            }

            // and if there are some annotations, add it to the result set
            if (!annotatedArgumentPair.mTurkAssignments.isEmpty()) {
                annotatedArgumentPairs.add(annotatedArgumentPair);
            }
        }

        if (!annotatedArgumentPairs.isEmpty()) {
            File outputFile = new File(outputDir, file.getName());
            XStreamTools.toXML(annotatedArgumentPairs, outputFile);

            System.out.println("Saved " + annotatedArgumentPairs.size() + " annotated pairs to " + outputFile);
            totalSavedPairs += annotatedArgumentPairs.size();
        }
    }

    System.out.println("Total saved " + totalSavedPairs + " pairs");

    // print assignments with empty reasons
    if (!assignmentsWithEmptyReason.isEmpty()) {
        System.out.println(
                "== Assignments with empty reason:\nassignmentIdToReject\tassignmentIdToRejectComment");
        for (String assignmentId : assignmentsWithEmptyReason) {
            System.out.println(
                    assignmentId + "\t\"Dear worker, you did not fill the required field with a reason.\"");
        }
    }

}

From source file:Main.java

/**
 * Returns a sorted copy of the provided collection of things. Uses the provided comparator to sort.
 *///w ww  .j  av a  2 s .  c  o m
public static <T> List<T> sort(Iterable<? extends T> things, Comparator<? super T> comparator) {
    List<T> copy = toMutableList(things);
    Collections.sort(copy, comparator);
    return copy;
}

From source file:Main.java

public static String dumpLuxLevel() {
    String result = "";
    if (mLevelSet == null)
        mLevelSet = mContext.getSharedPreferences(PREFER, Context.MODE_WORLD_READABLE).getStringSet(LEVELSET,
                null);/*from  w  w w.  j  a  v  a  2  s . c  o m*/
    if (mLevelSet != null) {
        ArrayList<String> array = Collections.list(Collections.enumeration(mLevelSet));
        Collections.sort(array, mComparator);
        result = array.toString();
    }
    return result;
}

From source file:Main.java

public static int hashCode(List list) {
    if (list == null) {
        return 0;
    }/*from w w w .  j  a  va 2s .  co  m*/
    if (list.isEmpty()) {
        return 1;
    }
    ArrayList<?> tmp = new ArrayList<>(list);
    Collections.sort(tmp, (o1, o2) -> Integer.compare(o1.hashCode(), o2.hashCode()));
    return tmp.hashCode();
}

From source file:Main.java

private static Map sortByComparator(Map unsortMap) {
    List list = new LinkedList(unsortMap.entrySet());
    Collections.sort(list, new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue());
        }/*from   ww w .j av  a 2 s  .co m*/
    });
    Map sortedMap = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    return sortedMap;
}