Example usage for java.util Collections reverseOrder

List of usage examples for java.util Collections reverseOrder

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public static <T> Comparator<T> reverseOrder() 

Source Link

Document

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {

    int[] intArray = new int[] { 4, 1, 3, -23 };
    Arrays.sort(intArray);/*from  w w w .ja v a  2  s.c  o m*/
    // [-23, 1, 3, 4]

    String[] strArray = new String[] { "z", "a", "C" };
    Arrays.sort(strArray);
    // [C, a, z]

    // Case-insensitive sort
    Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
    // [a, C, z]

    // Reverse-order sort
    Arrays.sort(strArray, Collections.reverseOrder());
    // [z, a, C]

    // Case-insensitive reverse-order sort
    Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
    Collections.reverse(Arrays.asList(strArray));
    // [z, C, a]
}

From source file:Main.java

public static void main(String[] args) {
    List<String> colours = new ArrayList<String>();
    colours.add("red");
    colours.add("green");
    colours.add("blue");
    colours.add("yellow");
    colours.add("cyan");
    colours.add("white");
    colours.add("black");

    Collections.sort(colours);/*from   w  ww  .ja va2 s . co m*/
    System.out.println(Arrays.toString(colours.toArray()));

    Collections.sort(colours, Collections.reverseOrder());
    System.out.println(Arrays.toString(colours.toArray()));
}

From source file:Company.java

public static void main(String args[]) {
    Employee emps[] = { new Employee("Finance", "Degree, Debbie"), new Employee("Finance", "Grade, Geri"),
            new Employee("Finance", "Extent, Ester"), new Employee("Engineering", "Measure, Mary"),
            new Employee("Engineering", "Amount, Anastasia"), new Employee("Engineering", "Ratio, Ringo"),
            new Employee("Sales", "Stint, Sarah"), new Employee("Sales", "Pitch, Paula"),
            new Employee("Support", "Rate, Rhoda"), };
    Set set = new TreeSet(Arrays.asList(emps));
    System.out.println(set);// w w  w  .j a  v  a  2 s .co  m
    Set set2 = new TreeSet(Collections.reverseOrder());
    set2.addAll(Arrays.asList(emps));
    System.out.println(set2);

    Set set3 = new TreeSet(new EmpComparator());
    for (int i = 0, n = emps.length; i < n; i++) {
        set3.add(emps[i]);
    }
    System.out.println(set3);
}

From source file:EmpComparator.java

public static void main(String args[]) {
    String names[] = { "Bart", "Hugo", "Lisa", "Marge", "Homer", "Maggie", "Roy" };

    // Convert to list
    List list = new ArrayList(Arrays.asList(names));

    // Ensure list sorted
    Collections.sort(list);/*from  www.  j av  a 2s  .c o  m*/
    System.out.println("Sorted list: [length: " + list.size() + "]");
    System.out.println(list);

    // Search for element in list
    int index = Collections.binarySearch(list, "Maggie");
    System.out.println("Found Maggie @ " + index);

    // Search for element not in list
    index = Collections.binarySearch(list, "Jimbo Jones");
    System.out.println("Didn't find Jimbo Jones @ " + index);

    // Insert
    int newIndex = -index - 1;
    list.add(newIndex, "Jimbo Jones");
    System.out.println("With Jimbo Jones added: [length: " + list.size() + "]");
    System.out.println(list);

    // Min should be Bart
    System.out.println(Collections.min(list));
    // Max should be Roy
    System.out.println(Collections.max(list));

    Comparator comp = Collections.reverseOrder();

    // Reversed Min should be Roy
    System.out.println(Collections.min(list, comp));
    // Reversed Max should be Bart
    System.out.println(Collections.max(list, comp));
}

From source file:Main.java

public static SortedSet reverseSortedSet(int[] ints) {
    TreeSet sortedSet = new TreeSet(Collections.reverseOrder());
    for (int i = 0; i < ints.length; i++) {
        sortedSet.add(new Integer(ints[i]));
    }/*from   w ww  . ja va2 s  .com*/

    return sortedSet;
}

From source file:Main.java

/**
 * Convenience method for sorting a list by either ascending or descending
 * Ascending is exactly the same as calling Collections.sort(list)
 * Descending is exactly the same as calling Collections.sort(list, Collections.reverseOrder())
 * /*from w ww  .j  a  v  a  2 s . c  o m*/
 * @param list
 * @param isAscending
 */
public static <T extends Comparable<? super T>> void sort(List<T> list, boolean isAscending) {
    if (isAscending) {
        Collections.sort(list);
    } else { //is dec
        Collections.sort(list, Collections.reverseOrder());
    }
}

From source file:com.coderadar.controller.MainController.java

public static void main(String[] args) {
    List<String> sortList = new ArrayList<String>();
    sortList.add("tc-5.5.x");
    sortList.add("tc-6.0.x");
    sortList.add("tc-7.0.x");
    sortList.add("tc-8.0.x");
    sortList.add("trunk");
    Collections.sort(sortList);/*from  w  w w .ja  v  a  2  s  .  c  o m*/
    Collections.sort(sortList, Collections.reverseOrder());
    System.out.println("");
}

From source file:com.yahoo.egads.utilities.AutoSensitivity.java

public static Float getLowDensitySensitivity(Float[] data, float sDAutoSensitivy, float amntAutoSensitivity) {
    Float toReturn = Float.POSITIVE_INFINITY;
    Arrays.sort(data, Collections.reverseOrder());
    while (data.length > 0) {

        ArrayList<Float> fData = new ArrayList<Float>();
        fData.add(data[0]);/* w w  w . j a  v  a  2 s  . co  m*/
        data = ((Float[]) ArrayUtils.remove(data, 0));

        Float centroid = (float) fData.get(0);
        Float maxDelta = (float) sDAutoSensitivy * StatsUtils.getSD(data, StatsUtils.getMean(data));

        logger.debug("AutoSensitivity: Adding: " + fData.get(0) + " SD: " + maxDelta);

        // Add points while it's in the same cluster or not part of the other cluster.
        String localDebug = null;
        while (data.length > 0 && (centroid - data[0]) <= ((float) (maxDelta))) {
            float maxDeltaInit = maxDelta;
            fData.add(data[0]);
            data = ((Float[]) ArrayUtils.remove(data, 0));
            Float[] tmp = new Float[fData.size()];
            tmp = fData.toArray(tmp);
            centroid = StatsUtils.getMean(tmp);

            if (data.length > 0) {
                Float sdOtherCluster = (float) StatsUtils.getSD(data, StatsUtils.getMean(data));
                maxDelta = sDAutoSensitivy * sdOtherCluster;
                logger.debug(
                        "AutoSensitivity: Adding: " + data[0] + " SD: " + maxDeltaInit + " SD': " + maxDelta);
            }
        }
        if (data.length > 0) {
            logger.debug("AutoSensitivity: Next Point I would have added is " + data[0]);
        }

        if (((double) fData.size() / (double) data.length) > amntAutoSensitivity) {
            // Cannot do anomaly detection.
            logger.debug("AutoSensitivity: Returning " + toReturn + " data size: " + data.length
                    + " fData.size: " + fData.size());
            return toReturn;
        }

        toReturn = fData.get(fData.size() - 1);
        logger.debug("AutoSensitivity: Updating toReturn:  " + toReturn + " SD: " + maxDelta);
        return toReturn;
    }
    return toReturn;
}

From source file:com.thinkbiganalytics.discovery.parsers.csv.CSVAutoDetect.java

private static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> map) {
    return map.entrySet().stream().sorted(Map.Entry.comparingByValue(Collections.reverseOrder())).collect(
            Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}

From source file:edu.upenn.egricelab.AlignerBoost.FilterSAMAlignPE.java

public static void main(String[] args) {
    if (args.length == 0) {
        printUsage();/*  w  ww  .j av  a 2  s  .c  o  m*/
        return;
    }
    try {
        parseOptions(args);
    } catch (IllegalArgumentException e) {
        System.err.println("Error: " + e.getMessage());
        printUsage();
        return;
    }

    // Read in chrList, if specified
    if (chrFile != null) {
        chrFilter = new HashSet<String>();
        try {
            BufferedReader chrFilterIn = new BufferedReader(new FileReader(chrFile));
            String chr = null;
            while ((chr = chrFilterIn.readLine()) != null)
                chrFilter.add(chr);
            chrFilterIn.close();
            if (verbose > 0)
                System.err.println(
                        "Only looking at alignments on " + chrFilter.size() + " specified chromosomes");
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
            return;
        }
    }

    if (verbose > 0) {
        // Start the processMonitor
        processMonitor = new Timer();
        // Start the ProcessStatusTask
        statusTask = new ProcessStatusTask();
        // Schedule to show the status every 1 second
        processMonitor.scheduleAtFixedRate(statusTask, 0, statusFreq);
    }

    // Read in known SNP file, if specified
    if (knownSnpFile != null) {
        if (verbose > 0)
            System.err.println("Checking known SNPs from user specified VCF file");
        knownVCF = new VCFFileReader(new File(knownSnpFile));
    }

    SamReaderFactory readerFac = SamReaderFactory.makeDefault();
    SAMFileWriterFactory writerFac = new SAMFileWriterFactory();
    if (!isSilent)
        readerFac.validationStringency(ValidationStringency.LENIENT); // use LENIENT stringency
    else
        readerFac.validationStringency(ValidationStringency.SILENT); // use SILENT stringency

    SamReader in = readerFac.open(new File(inFile));
    SAMFileHeader inHeader = in.getFileHeader();
    if (inHeader.getGroupOrder() == GroupOrder.reference && inHeader.getSortOrder() == SortOrder.coordinate)
        System.err.println("Warning: Input file '" + inFile
                + "' might be sorted by coordinate and cannot be correctly processed!");

    SAMFileHeader header = inHeader.clone(); // copy the inFile header as outFile header
    // Add new programHeader
    SAMProgramRecord progRec = new SAMProgramRecord(progName);
    progRec.setProgramName(progName);
    progRec.setProgramVersion(progVer);
    progRec.setCommandLine(StringUtils.join(" ", args));
    header.addProgramRecord(progRec);
    //System.err.println(inFile + " groupOrder: " + in.getFileHeader().getGroupOrder() + " sortOrder: " + in.getFileHeader().getSortOrder());
    // reset the orders
    header.setGroupOrder(groupOrder);
    header.setSortOrder(sortOrder);

    // write SAMHeader
    String prevID = null;
    SAMRecord prevRecord = null;
    List<SAMRecord> alnList = new ArrayList<SAMRecord>();
    List<SAMRecordPair> alnPEList = null;

    // Estimate fragment length distribution by scan one-pass through the alignments
    SAMRecordIterator results = in.iterator();
    if (!NO_ESTIMATE) {
        if (verbose > 0) {
            System.err.println("Estimating insert fragment size distribution ...");
            statusTask.reset();
            statusTask.setInfo("alignments scanned");
        }
        long N = 0;
        double fragL_S = 0; // fragLen sum
        double fragL_SS = 0; // fragLen^2 sum
        while (results.hasNext()) {
            SAMRecord record = results.next();
            if (verbose > 0)
                statusTask.updateStatus();
            if (record.getFirstOfPairFlag() && !record.isSecondaryOrSupplementary()) {
                double fragLen = Math.abs(record.getInferredInsertSize());
                if (fragLen != 0 && fragLen >= MIN_FRAG_LEN && fragLen <= MAX_FRAG_LEN) { // only consider certain alignments
                    N++;
                    fragL_S += fragLen;
                    fragL_SS += fragLen * fragLen;
                }
                // stop estimate if already enough
                if (MAX_ESTIMATE_SCAN > 0 && N >= MAX_ESTIMATE_SCAN)
                    break;
            }
        }
        if (verbose > 0)
            statusTask.finish();
        // estimate fragment size
        if (N >= MIN_ESTIMATE_BASE) { // override command line values
            MEAN_FRAG_LEN = fragL_S / N;
            SD_FRAG_LEN = Math.sqrt((N * fragL_SS - fragL_S * fragL_S) / (N * (N - 1)));
            String estStr = String.format("Estimated fragment size distribution: N(%.1f, %.1f)", MEAN_FRAG_LEN,
                    SD_FRAG_LEN);
            if (verbose > 0)
                System.err.println(estStr);
            // also add the estimation to comment
            header.addComment(estStr);
        } else {
            System.err.println(
                    "Unable to estimate the fragment size distribution due to too few observed alignments");
            System.err.println(
                    "You have to specify the '--mean-frag-len' and '--sd-frag-len' on the command line and re-run this step");
            statusTask.cancel();
            processMonitor.cancel();
            return;
        }
        // Initiate the normal model
        normModel = new NormalDistribution(MEAN_FRAG_LEN, SD_FRAG_LEN);
        // reset the iterator, if necessary
        if (in.type() == SamReader.Type.SAM_TYPE) {
            try {
                in.close();
            } catch (IOException e) {
                System.err.println(e.getMessage());
            }
            in = readerFac.open(new File(inFile));
        }
        results.close();
        results = in.iterator();
    } // end of NO_ESTIMATE

    SAMFileWriter out = OUT_IS_SAM ? writerFac.makeSAMWriter(header, false, new File(outFile))
            : writerFac.makeBAMWriter(header, false, new File(outFile));

    // check each alignment again
    if (verbose > 0) {
        System.err.println("Filtering alignments ...");
        statusTask.reset();
        statusTask.setInfo("alignments processed");
    }
    while (results.hasNext()) {
        SAMRecord record = results.next();
        if (verbose > 0)
            statusTask.updateStatus();
        String ID = record.getReadName();
        // fix read and quality string for this read, if is a secondary hit from multiple hits, used for BWA alignment
        if (ID.equals(prevID) && record.getReadLength() == 0)
            SAMAlignFixer.fixSAMRecordRead(record, prevRecord);
        if (chrFilter != null && !chrFilter.contains(record.getReferenceName())) {
            prevID = ID;
            prevRecord = record;
            continue;
        }

        // fix MD:Z string for certain aligners with invalid format (i.e. seqAlto)
        if (fixMD)
            SAMAlignFixer.fixMisStr(record);

        // fix alignment, ignore if failed (unmapped or empty)
        if (!SAMAlignFixer.fixSAMRecord(record, knownVCF, DO_1DP)) {
            prevID = ID;
            prevRecord = record;
            continue;
        }
        if (!record.getReadPairedFlag()) {
            System.err.println("Error: alignment is not from a paired-end read at\n" + record.getSAMString());
            out.close();
            statusTask.cancel();
            processMonitor.cancel();
            return;
        }

        if (!ID.equals(prevID) && prevID != null || !results.hasNext()) { // a non-first new ID meet, or end of alignments
            // create alnPEList from filtered alnList
            alnPEList = createAlnPEListFromAlnList(alnList);
            //System.err.printf("%d alignments for %s transformed to %d alnPairs%n", alnList.size(), prevID, alnPEList.size());
            int totalPair = alnPEList.size();
            // filter highly unlikely PEhits
            filterPEHits(alnPEList, MIN_ALIGN_RATE, MIN_IDENTITY);
            // calculate posterior mapQ for each pair
            calcPEHitPostP(alnPEList, totalPair, MAX_HIT);
            // filter hits by mapQ
            if (MIN_MAPQ > 0)
                filterPEHits(alnPEList, MIN_MAPQ);

            // sort the list first with an anonymous class of comparator, with DESCREASING order
            Collections.sort(alnPEList, Collections.reverseOrder());
            // control max-best
            if (MAX_BEST != 0 && alnPEList.size() > MAX_BEST) { // potential too much best hits
                int nBestStratum = 0;
                int bestMapQ = alnPEList.get(0).getPEMapQ(); // best mapQ from first PE
                for (SAMRecordPair pr : alnPEList)
                    if (pr.getPEMapQ() == bestMapQ)
                        nBestStratum++;
                    else
                        break; // stop searching for sorted list
                if (nBestStratum > MAX_BEST)
                    alnPEList.clear();
            }
            // filter alignments with auxiliary filters
            if (!MAX_SENSITIVITY)
                filterPEHits(alnPEList, MAX_SEED_MIS, MAX_SEED_INDEL, MAX_ALL_MIS, MAX_ALL_INDEL);

            // report remaining secondary alignments, up-to MAX_REPORT
            for (int i = 0; i < alnPEList.size() && (MAX_REPORT == 0 || i < MAX_REPORT); i++) {
                SAMRecordPair repPair = alnPEList.get(i);
                if (doUpdateBit)
                    repPair.setNotPrimaryAlignmentFlags(i != 0);
                int nReport = MAX_REPORT == 0 ? Math.min(alnPEList.size(), MAX_REPORT) : alnPEList.size();
                int nFiltered = alnPEList.size();
                if (repPair.fwdRecord != null) {
                    repPair.fwdRecord.setAttribute("NH", nReport);
                    repPair.fwdRecord.setAttribute("XN", nFiltered);
                    out.addAlignment(repPair.fwdRecord);
                }
                if (repPair.revRecord != null) {
                    repPair.revRecord.setAttribute("NH", nReport);
                    repPair.revRecord.setAttribute("XN", nFiltered);
                    out.addAlignment(repPair.revRecord);
                }
            }
            // reset list
            alnList.clear();
            alnPEList.clear();
        }
        // update
        if (!ID.equals(prevID)) {
            prevID = ID;
            prevRecord = record;
        }
        alnList.add(record);
    } // end while
    try {
        in.close();
        out.close();
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
    // Terminate the monitor task and monitor
    if (verbose > 0) {
        statusTask.cancel();
        statusTask.finish();
        processMonitor.cancel();
    }
}