Example usage for java.util Arrays sort

List of usage examples for java.util Arrays sort

Introduction

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

Prototype

public static <T> void sort(T[] a, Comparator<? super T> c) 

Source Link

Document

Sorts the specified array of objects according to the order induced by the specified comparator.

Usage

From source file:com.yahoo.platform.yuitest.coverage.results.FileCoverageReport.java

/**
 * Creates the FileFunction objects for the file.
 * @throws org.json.JSONException/*from w w w. j av  a  2  s  . c  om*/
 */
private void createFileFunctions() throws JSONException {
    JSONObject functionData = report1.getJSONObject("functions");
    String[] keys = JSONObject.getNames(functionData);
    functions = new FileFunction[keys.length];

    for (int i = 0; i < keys.length; i++) {
        functions[i] = new FileFunction(keys[i], functionData.optInt(keys[i], -1));
    }

    Arrays.sort(functions, new FileFunctionComparator());
}

From source file:de.tor.tribes.util.report.ReportManager.java

@Override
public String[] getGroups() {
    String[] groups = super.getGroups();
    Arrays.sort(groups, new Comparator<String>() {

        @Override/*from w w  w . j  a  v a2  s. c  o m*/
        public int compare(String o1, String o2) {
            if (o1.equals(DEFAULT_GROUP) || o1.equals(FARM_SET)) {
                return -1;
            } else if (o2.equals(DEFAULT_GROUP) || o2.equals(FARM_SET)) {
                return 1;
            } else {
                return String.CASE_INSENSITIVE_ORDER.compare(o1, o2);
            }
        }
    });
    return groups;
}

From source file:SortUtils.java

/**
 * Test method//from  ww  w . ja  v  a 2 s. com
 */
public static void main(String[] args) {
    Comparator cmp = new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((Comparable) o1).compareTo(o2);
        }
    };

    int n = 1000000;
    if (args.length == 1)
        try {
            n = Integer.parseInt(args[0]);
        } catch (Exception e) {
            System.err.println(e);
        }
    System.out.println("Generating " + n + " random integers...");
    java.util.Random random = new java.util.Random();
    Integer[] data = new Integer[n];
    for (int i = 0; i < n; i++) {
        data[i] = new Integer(Math.abs(random.nextInt()));
        //      data[i] = new Integer(i);
    }
    int[] indices;
    long time;

    System.out.print("Arrays.sort...");
    time = System.currentTimeMillis();
    Integer[] clone = (Integer[]) data.clone();
    Arrays.sort(clone, cmp);
    System.out.println(System.currentTimeMillis() - time + "ms");

    System.out.print("quicksort...");
    indices = identity(n);
    time = System.currentTimeMillis();
    sort(indices, data, cmp, false);
    System.out.println(System.currentTimeMillis() - time + "ms");
    for (int i = 1; i < n; i++)
        if (cmp.compare(data[indices[i - 1]], data[indices[i]]) > 0)
            System.err.println("proplem: quickSort at " + i);

    System.out.print("quicksort stable...");
    //    indices = identity(n);
    time = System.currentTimeMillis();
    sort(indices, data, cmp, true);
    System.out.println(System.currentTimeMillis() - time + "ms");
    for (int i = 1; i < n; i++) {
        int res = cmp.compare(data[indices[i - 1]], data[indices[i]]);
        if (res > 0)
            System.err.println("proplem: quickSort stable at " + i);
        if (res == 0 && indices[i - 1] > indices[i])
            System.err.println("proplem: quickSort stable (not stable) at " + i);
    }

    //    System.out.print("cheapsort...");
    //    time = System.currentTimeMillis();
    //    indices = cheapSort(data, cmp);
    //    System.out.println(System.currentTimeMillis()-time + "ms");
    //    for (int i = 1; i < n; i++)
    //      if (cmp.compare(data[indices[i-1]], data[indices[i]]) > 0)
    //        System.err.println("proplem: cheapSort at " + i);

    System.out.print("permutate copy...");
    time = System.currentTimeMillis();
    Object[] data_copy = permute(inverse(indices), data, true);
    System.out.println(System.currentTimeMillis() - time + "ms");
    for (int i = 1; i < n; i++)
        if (cmp.compare(data_copy[i - 1], data_copy[i]) > 0)
            System.err.println("proplem: permute copy at " + i);

    System.out.print("permutate original...");
    time = System.currentTimeMillis();
    permute(inverse(indices), data, false);
    System.out.println(System.currentTimeMillis() - time + "ms");
    for (int i = 1; i < n; i++)
        if (cmp.compare(data[i - 1], data[i]) > 0)
            System.err.println("proplem: permute original at " + i);
}

From source file:com.walmartlabs.mupd8.application.Config.java

public Config(File directory) throws IOException {
    File[] files = directory.listFiles(new FilenameFilter() {
        @Override// w  ww  .  j av a 2 s  . c  o m
        public boolean accept(File dir, String name) {
            return name.endsWith(".cfg");
        }
    });
    if (files == null) {
        throw new FileNotFoundException("Configuration path " + directory.toString() + " is not a directory.");
    }
    Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    applyFiles(configuration, files);
    workerJSONs = extractWorkerJSONs(configuration);
}

From source file:com.web.vehiclerouting.optaplanner.common.persistence.AbstractSolutionImporter.java

public void convertAll() {
    File[] inputFiles = inputDir.listFiles();
    Arrays.sort(inputFiles, new ProblemFileComparator());
    for (File inputFile : inputFiles) {
        if (acceptInputFile(inputFile) && acceptInputFileDuringBulkConvert(inputFile)) {
            String inputFileName = inputFile.getName();
            String outputFileName = inputFileName.substring(0,
                    inputFileName.length() - getInputFileSuffix().length()) + getOutputFileSuffix();
            File outputFile = new File(outputDir, outputFileName);
            convert(inputFile, outputFile);
        }//from   ww w  .ja v  a2 s  .  c o m
    }
}

From source file:com.logsniffer.model.file.WildcardLogSourceTest.java

@Test
public void testLogsResolving() throws IOException {
    File tmp = File.createTempFile("sdkj", "jk");
    tmp.deleteOnExit();// w  ww  .j ava2 s .c om
    File tmpFolder1 = new File(tmp.getPath() + "d", "f1");
    tmpFolder1.mkdirs();
    tmpFolder1.deleteOnExit();
    File tmpFolder2 = new File(tmp.getPath() + "d", "f2");
    tmpFolder2.mkdirs();
    tmpFolder2.deleteOnExit();
    FileUtils.write(new File(tmpFolder1, "1.txt"), "txt");
    FileUtils.write(new File(tmpFolder1, "2.txt"), "txt");
    FileUtils.write(new File(tmpFolder1, "3.log"), "log");
    FileUtils.write(new File(tmpFolder2, "22.txt"), "txt");
    File tmpDir = new File(tmpFolder2, "folder.txt");
    tmpDir.mkdir();
    tmpDir.deleteOnExit();

    // Check now
    WildcardLogsSource source = new WildcardLogsSource();
    source.setPattern(tmp.getPath() + "d/*.txt");
    Assert.assertEquals(0, source.getLogs().size());
    source.setPattern(tmp.getPath() + "d/**/*.txt");
    Log[] logs = source.getLogs().toArray(new Log[0]);
    Assert.assertEquals(3, logs.length);
    Arrays.sort(logs, new Comparator<Log>() {
        @Override
        public int compare(final Log o1, final Log o2) {
            return o1.getPath().compareTo(o2.getPath());
        }
    });
    Assert.assertTrue(logs[0].getPath().endsWith("1.txt"));
    Assert.assertTrue(logs[1].getPath().endsWith("2.txt"));
    Assert.assertTrue(logs[2].getPath().endsWith("22.txt"));
}

From source file:i2p.bote.web.PeerInfoTag.java

@Override
public void doTag() {
    PageContext pageContext = (PageContext) getJspContext();
    JspWriter out = pageContext.getOut();

    try {/* www  .  j  a v a 2  s .  c om*/
        // Print DHT peer info
        DhtPeerStats dhtStats = I2PBote.getInstance().getDhtStats();
        if (dhtStats == null)
            return;

        int numDhtPeers = dhtStats.getData().size();

        // Get a sorted list of relay peers
        RelayPeer[] relayPeers = I2PBote.getInstance().getRelayPeers().toArray(new RelayPeer[0]);
        Arrays.sort(relayPeers, new Comparator<RelayPeer>() {
            @Override
            public int compare(RelayPeer peer1, RelayPeer peer2) {
                return peer2.getReachability() - peer1.getReachability();
            }
        });

        // Print charts
        out.println("<div class=\"network-charts\">");
        out.println("<div class=\"chart\">");
        out.println("<img src=\"displayChart?filename=" + createDhtChart(dhtStats) + "\"/>");
        out.println("<div class=\"chart-text\">" + numDhtPeers + "</div>");
        out.println("</div>");
        out.println("<div class=\"chart\">");
        out.println("<img src=\"displayChart?filename=" + createRelayChart(relayPeers) + "\"/>");
        out.println("<div class=\"chart-text\">" + relayPeers.length + "</div>");
        out.println("</div>");
        out.println("</div>");
        out.println("<br>");

        out.println("<span class=\"subheading\">" + _t("Kademlia Peers:") + " " + numDhtPeers + "</span>");
        if (numDhtPeers > 0) {
            out.println("<table");

            // header
            out.println("<tr>");
            for (String columnHeader : dhtStats.getHeader())
                out.println("<th>" + columnHeader + "</th>");
            out.println("</tr>");

            // data
            for (List<String> row : dhtStats.getData()) {
                out.println("<tr>");
                for (String cellData : row)
                    out.println("<td class=\"ellipsis\">" + cellData + "</td>");
                out.println("</tr>");
            }

            out.println("</table>");
        }

        out.println("<br/>");

        // Print relay peer info
        out.println("<span class=\"subheading\">" + _t("Relay Peers:") + " " + relayPeers.length + "</span>");
        if (relayPeers.length > 0) {
            out.println("<table");
            out.println("<tr>");
            out.println("<th>" + _t("Peer") + "</th>");
            out.println("<th>" + _t("I2P Destination") + "</th>");
            out.println("<th>" + _t("Reachability %") + "</th>");
            out.println("</tr>");

            int i = 1;
            for (RelayPeer peer : relayPeers) {
                out.println("<tr>");
                out.println("<td>" + i + "</td>");
                out.println("<td class=\"ellipsis\">" + Util.toBase32(peer) + "</td>");
                int reachability = peer.getReachability();
                out.println("<td>" + (reachability == 0 ? _t("Untested") : reachability) + "</td>");
                out.println("</tr>");
                i++;
            }
            out.println("</table>");
        }

        out.println("<br/>");

        // List banned peers
        Collection<BannedPeer> bannedPeers = I2PBote.getInstance().getBannedPeers();
        out.println("<span class=\"subheading\">" + _t("Banned Peers:") + " " + bannedPeers.size() + "</span>");
        if (bannedPeers.size() > 0) {
            out.println("<table>");
            out.println("<tr>");
            out.println("<th>" + _t("Peer") + "</th>");
            out.println("<th>" + _t("Destination Hash") + "</th>");
            out.println("<th>" + _t("Ban Reason") + "</th>");
            out.println("</tr>");

            int peerIndex = 1;
            for (BannedPeer peer : bannedPeers) {
                out.println("<tr>");
                out.println("<td>" + peerIndex++ + "</td>");
                out.println("<td class=\"ellipsis\">" + Util.toBase32(peer.getDestination()) + "</td>");
                out.println("<td>" + (peer.getBanReason() == null ? "" : peer.getBanReason()) + "</td>");
                out.println("</tr>");
            }

            out.println("</table>");
        }
    } catch (IOException e) {
        log.error("Can't write output to HTML page", e);
    }
}

From source file:com.haulmont.cuba.core.sys.LogControlImpl.java

@Override
public List<String> getLogFileNames() {
    List<String> filenames = new ArrayList<>();
    if (logDir.isDirectory()) {
        File[] files = logDir.listFiles();
        if (files != null) {
            Arrays.sort(files, (a, b) -> Long.compare(b.lastModified(), a.lastModified()));
            for (File f : files) {
                if (f.isFile())
                    filenames.add(f.getName());
            }//from   w  ww  .ja  v  a  2 s .c  o m
        }
    }
    return filenames;
}

From source file:net.dv8tion.jda.core.utils.cache.impl.SortedSnowflakeCacheView.java

@Nonnull
@Override//from  w w w  .  java  2  s. co  m
@SuppressWarnings("unchecked")
public Iterator<T> iterator() {
    T[] arr = elements.values(emptyArray);
    Arrays.sort(arr, comparator);
    return new ObjectArrayIterator<>(arr);
}

From source file:com.feedzai.fos.server.remote.impl.RemoteInterfacesTest.java

private void testMatch(Class<?> api, Class<?> remote, int remoteFieldAdditions) {
    Method[] apiMethods = api.getMethods();
    Method[] remoteMethods = remote.getMethods();

    Arrays.sort(apiMethods, buildComparator());
    Arrays.sort(remoteMethods, buildComparator());

    // Checks if @RemoteInterface is different from the class/interface itself.
    assertNotSame(//from   w  w  w.  j  a va 2s  .  com
            String.format("@RemoteInterface cannot be the same for the class name in %s", api.getSimpleName()),
            api, remote);
    // Checks if the remote implementation can be assigned to Remote (i.e. if in the hierarchy extends/implements Remote).
    assertTrue(
            String.format("'%s' does not implement '%s'", remote.getSimpleName(), Remote.class.getSimpleName()),
            Remote.class.isAssignableFrom(remote));

    assertEquals(desc(api, null, "Number of methods matches"), apiMethods.length, remoteMethods.length);

    for (int i = 0; i < apiMethods.length; i++) {
        // Check if the names match
        Method expected = apiMethods[i];
        Method actual = remoteMethods[i];

        assertEquals(desc(api, actual, "Names match"), expected.getName(), actual.getName());
        assertTrue(desc(api, actual, "Number of arguments matches"), expected.getParameterTypes().length
                - actual.getParameterAnnotations().length <= remoteFieldAdditions);

        boolean remoteOrException = false;
        for (Class klass : actual.getExceptionTypes()) {
            remoteOrException = Exception.class.equals(klass) || RemoteException.class.equals(klass);
            if (remoteOrException) {
                break;
            }
        }

        // Checks if remote implementations throw Exception or RemoteException.
        assertTrue(desc(remote, actual,
                String.format("%s does not throw either RemoteException or Exception", actual.getName())),
                remoteOrException);
    }
}