List of usage examples for java.util Comparator Comparator
Comparator
From source file:Main.java
public static String[] sortQualities(String[] qualities) { Arrays.sort(qualities, new Comparator<String>() { @Override/*from w w w. j a v a2 s .com*/ public int compare(String lhs, String rhs) { if (lhs.contains("p") && rhs.contains("p")) { int q1 = Integer.parseInt(lhs.substring(0, lhs.indexOf('p'))); int q2 = Integer.parseInt(rhs.substring(0, rhs.indexOf('p'))); if (q1 < q2) { return 1; } else if (q1 < q2) { return -1; } else { return 0; } } if (lhs.equals("3D")) return 1; return 0; } }); return qualities; }
From source file:Main.java
public static <T extends Comparable> Integer[] getSortedArrayIndexes(final T[] array) { Integer[] indexes = new Integer[array.length]; for (int i = 0; i < indexes.length; i++) { indexes[i] = i;// w w w . j a va2 s. c o m } Arrays.sort(indexes, new Comparator<Integer>() { @Override public int compare(Integer aIndex, Integer bIndex) { return array[aIndex].compareTo(array[bIndex]); } }); return indexes; }
From source file:Main.java
/** * Returns the ordered keys of the given map * /*w w w .j a v a 2 s . c om*/ * @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:Main.java
public static Comparator<String> createFuzzyKeyComparator() { return new Comparator<String>() { @Override/* w w w. j a va 2s .com*/ public int compare(String key1, String key2) { String imageUri1 = key1.substring(0, key1.lastIndexOf(URI_AND_SIZE_SEPARATOR)); String imageUri2 = key2.substring(0, key2.lastIndexOf(URI_AND_SIZE_SEPARATOR)); return imageUri1.compareTo(imageUri2); } }; }
From source file:CompTest.java
public static Comparator stringComparator() { return new Comparator() { public int compare(Object o1, Object o2) { String s1 = (String) o1; String s2 = (String) o2; int len1 = s1.length(); int len2 = s2.length(); int n = Math.min(len1, len2); char v1[] = s1.toCharArray(); char v2[] = s2.toCharArray(); int pos = 0; while (n-- != 0) { char c1 = v1[pos]; char c2 = v2[pos]; if (c1 != c2) { return c1 - c2; }//from w w w . j a v a 2 s .com pos++; } return len1 - len2; } }; }
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 a2 s . c o 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; }
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 ww w . ja v a 2 s. c o 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
public static <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> entriesSortedByValues( Map<K, V> map) {/* w ww . j a v a 2 s . c om*/ SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(new Comparator<Map.Entry<K, V>>() { @Override public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) { int res = e1.getValue().compareTo(e2.getValue()); /* Preserve items with equal values */ return res != 0 ? res : 1; } }); sortedEntries.addAll(map.entrySet()); return sortedEntries; }
From source file:Main.java
/** * The specified list will be sorted where then the small numbers comes first *//*from w w w . j a va 2 s. co m*/ public static <T> void sortInplaceLongReverse(List<Entry<T, Long>> entrySet) { Collections.sort(entrySet, new Comparator<Entry<T, Long>>() { @Override public int compare(Entry<T, Long> o1, Entry<T, Long> o2) { long i1 = o1.getValue(); long i2 = o2.getValue(); if (i1 < i2) return -1; else if (i1 > i2) return 1; else return 0; } }); }
From source file:de.tudarmstadt.lt.utilities.ListUtils.java
public static <T> int[] sortIdsByValue(final List<T> values, final Comparator<T> comparator) { Integer[] ids = new Integer[values.size()]; for (int id = 0; id < ids.length; ids[id] = id++) ;// ww w . jav a 2 s . co m Arrays.sort(ids, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return comparator.compare(values.get(o1), values.get(o2)); } }); return org.apache.commons.lang.ArrayUtils.toPrimitive(ids); }