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:ca.mcgill.cs.creco.logic.search.ProductSort.java

/**
 * Lists top 20 products according to their overall score in a category.
 * @param pCategoryID The category whose products are to be displayed
 * @return scoredproducts - The list of products.
 *///from w ww .  j a va 2s  .c  om
public List<Product> returnTopProducts(String pCategoryID) {
    Category category = aDataStore.getCategory(pCategoryID);
    if (category == null) {
        LOG.error("Invalid category ID: " + pCategoryID);
        return null;
    }

    List<Product> allScoredProducts = new ArrayList<Product>();
    Map<Double, Product> map = new TreeMap<Double, Product>(Collections.reverseOrder());
    List<Product> scoredProducts = new ArrayList<Product>();

    // The products get sorted as they are added to a tree map.
    for (Product product : category.getProducts()) {
        if (product.getOverallScore() != null) {
            map.put(product.getOverallScore(), product);
        }
    }

    // Repackage the treemap as a list.
    for (Product product : map.values()) {
        allScoredProducts.add(product);
    }

    // 20 products with the highest overall score will be displayed initially

    if (allScoredProducts.size() >= 20) {
        for (int i = 0; i < 20; i++) {
            scoredProducts.add(allScoredProducts.get(i));
        }

        return scoredProducts;
    } else {
        return allScoredProducts;
    }
}

From source file:controller.PostsController.java

@RequestMapping(value = "home", method = RequestMethod.GET)
public ModelAndView handleHome(HttpServletRequest request) {
    HttpSession session = request.getSession();
    if (session == null || !request.isRequestedSessionIdValid()) {
        return new ModelAndView("index");
    }/*from w ww. jav  a  2  s .c  om*/

    session.setAttribute("currentPage", "/home.htm");

    // Get all the posts sent to this user
    UsersEntity user = (UsersEntity) session.getAttribute("user");
    ArrayList<PostsEntity> posts = this.postsService.searchByTarget(user);

    // Add the posts sent by this user
    for (PostsEntity post : this.postsService.searchBySender(user)) {
        if (!posts.contains(post)) {
            posts.add(post);
        }
    }

    // Add the posts sent by friends
    for (UsersEntity friend : user.getFriends()) {
        for (PostsEntity post : this.postsService.searchBySender(friend)) {
            if (!posts.contains(post)) {
                posts.add(post);
            }
        }
    }

    Collections.sort(posts, Collections.reverseOrder());

    ModelAndView mv = new ModelAndView("home");
    mv.addObject("currentUser", user);
    mv.addObject("posts", posts);
    mv.addObject("nbNotifs", this.notifsService.searchByTarget(user).size());

    return mv;
}

From source file:lu.lippmann.cdb.weka.SilhouetteUtil.java

/**
 * res.get(clusterIdx) = silhouettes values map for instances 
 * @param result/*w ww.  ja  v  a  2 s  . c om*/
 * @return
 */
protected static Map<Integer, List<Double>> computeSilhouette(final Instances ds,
        final WekaClusteringResult result) {
    final List<Instances> clusters = result.getClustersList();
    final List<Double> res = new ArrayList<Double>();
    final int cs = clusters.size();

    final double[] ass = result.getAss();

    final EuclideanDistance euclidian = new EuclideanDistance(ds);
    //euclidian.setDontNormalize(true);
    ds.setClassIndex(-1);

    //Loop through every cluster
    final int dss = ds.numInstances();
    for (int i = 0; i < dss; i++) {
        final int clusterIndex = (int) ass[i];
        double distAo = -1;
        double distBo = Double.MAX_VALUE;
        boolean distanceIsZero = false;
        for (int j = 0; j < cs; j++) {
            //Compute distCo, for all C
            double distCo = 0;
            Instances cluster = result.getClustersList().get(j);
            final int cls = cluster.numInstances();
            for (int k = 0; k < cls; k++) {
                distCo += euclidian.distance(cluster.instance(k), ds.instance(i));
            }
            distCo /= cls;
            if (j != clusterIndex && distCo < distBo) {
                distBo = distCo;
            }

            if (j == clusterIndex) {
                if (distCo == 0) {
                    distanceIsZero = true;
                } else {
                    distAo = distCo;
                }
            }
        }
        if (distanceIsZero) {
            res.add(0d);
        } else {
            res.add((distBo - distAo) / Math.max(distAo, distBo));
        }
    }

    final Map<Integer, List<Double>> sils = new HashMap<Integer, List<Double>>();
    for (int i = 0; i < dss; i++) {
        final int clusterIndex = (int) ass[i];
        if (!sils.containsKey(clusterIndex)) {
            sils.put(clusterIndex, new ArrayList<Double>());
        }
        sils.get(clusterIndex).add(res.get(i));
    }
    for (final List<Double> list : sils.values()) {
        Collections.sort(list, Collections.reverseOrder());
    }
    return sils;

}

From source file:fm.last.citrine.service.LogFileManagerImpl.java

@Override
public List<String> findAllLogFiles() {
    String[] files = baseLogFolder.list(logFileFilter);
    List<String> logFiles = new ArrayList<String>();
    if (files != null) {
        for (String logFile : files) {
            logFiles.add(logFile);/*from   ww w  .  j a va2s .c o  m*/
        }
    }
    Collections.sort(logFiles, Collections.reverseOrder());
    return logFiles;
}

From source file:org.clueminer.clustering.algorithm.DBSCANParamEstim.java

/**
 *
 * @param dataset/*from w  ww . j a v  a 2  s .c o  m*/
 * @return
 */
private Double[] kdist(Dataset<E> dataset) {
    //k-dist graph data
    KNNSearch<Instance> knn = new LinearSearch(dataset);
    Neighbor[] neighbors;
    kdist = new Double[dataset.size()];
    for (int i = 0; i < dataset.size(); i++) {
        neighbors = knn.knn(dataset.get(i), k);
        kdist[i] = neighbors[k - 1].distance;
    }
    Arrays.sort(kdist, 0, kdist.length - 1, Collections.reverseOrder());

    return kdist;
}

From source file:org.kuali.kra.committee.lookup.keyvalue.CommitteeIdValuesFinder.java

/**
 * This method will return the list of all highest-sequence number committee instances.
 * Will always return non-null (but possibly empty) collection.
 *///from   w  w  w.  ja va  2s  .  com
protected List<Committee> getActiveCommittees() {
    ArrayList<Committee> returnCommitteeList = new ArrayList<Committee>();

    Collection<Committee> committees = this.getBusinessObjectService().findAll(Committee.class);
    // sort and iterate through to get only the latest instances
    if (CollectionUtils.isNotEmpty(committees)) {
        List<String> committeeIds = new ArrayList<String>();
        // only the active ones
        Collections.sort((List<Committee>) committees, Collections.reverseOrder());
        for (Committee committee : committees) {
            if (!committeeIds.contains(committee.getCommitteeId())) {
                returnCommitteeList.add(committee);
                committeeIds.add(committee.getCommitteeId());
            }
        }
    }

    return returnCommitteeList;
}

From source file:de.uzk.hki.da.cb.RestartIngestWorkflowAction.java

/**
 * Leaves only the representation with the SIP content. 
 *
 * @author Daniel M. de Oliveira//from  ww  w  . j  av  a  2  s  .  c o m
 * @throws IOException 
 */
private void revertDataFolderToSIPContent() throws IOException {

    List<String> filesC = Arrays.asList(object.getDataPath().toFile().list());
    Collections.sort(filesC, Collections.reverseOrder());
    String newestRep = filesC.iterator().next();
    if (newestRep.endsWith("+b")) {
        FileUtils.deleteDirectory(Path.makeFile(object.getDataPath(), newestRep));
        newestRep = newestRep.replace("+b", "+a");
    }

    File sipContent = Path.makeFile(object.getDataPath(), newestRep);
    File sipTemp = Path.makeFile(object.getPath(), "___sipContent");

    FileUtils.moveDirectory(sipContent, sipTemp);
    FileUtils.deleteDirectory(object.getDataPath().toFile());
    FileUtils.moveDirectory(sipTemp, object.getDataPath().toFile());
}

From source file:org.investovator.agentsimulation.multiasset.report.statistics.TopOrdersStatReport.java

protected List<Number> addToList(List<Order> list) {

    List<Number> priceList = new ArrayList<>();
    for (Order order : list) {
        priceList.add(order.getPrice());
    }//www  .  j  a va  2s . c o  m
    Collections.sort(priceList, Collections.reverseOrder());
    return priceList.size() > (size - 1) ? priceList.subList(0, size) : priceList;
}

From source file:org.mycontroller.standalone.api.jaxrs.BackupHandler.java

@GET
@Path("/backupList")
public Response getBackupList() {
    try {/*from  w w  w  . j av  a  2s  . co  m*/
        String[] filter = { "zip" };
        Collection<File> zipFiles = FileUtils.listFiles(
                FileUtils.getFile(ObjectFactory.getAppProperties().getBackupSettings().getBackupLocation()),
                filter, true);
        List<BackupFile> backupFiles = new ArrayList<BackupFile>();
        for (File zipFile : zipFiles) {
            if (zipFile.getName().contains(BackupRestore.FILE_NAME_IDENTITY)) {
                backupFiles.add(BackupFile.builder().name(zipFile.getName()).size(zipFile.length())
                        .timestamp(zipFile.lastModified()).absolutePath(zipFile.getAbsolutePath()).build());
            }

        }
        //Do order reverse
        Collections.sort(backupFiles, Collections.reverseOrder());
        return RestUtils.getResponse(Status.OK, backupFiles);
    } catch (Exception ex) {
        _logger.error("Error,", ex);
        return RestUtils.getResponse(Status.INTERNAL_SERVER_ERROR, new ApiError(ex.getMessage()));
    }

}

From source file:org.darkstar.batch.LuaScriptNpcIdUpdate.java

private void updateLuaScriptIds() {
    final Properties configProperties = DarkstarUtils.loadBatchConfiguration();
    final Properties npcIdShiftProperties = DarkstarUtils.loadShiftProperties(configProperties);
    final String darkStarRoot = configProperties.getProperty("darkstar_root", "");
    final String scriptsRoot = String.format("%s/%s", darkStarRoot, "scripts");
    final File scriptsDirectory = new File(scriptsRoot);
    final String[] extensions = new String[1];
    extensions[0] = "lua";

    if (!scriptsDirectory.exists() || !scriptsDirectory.isDirectory()) {
        throw new RuntimeException(String.format("Cannot Find Scripts Directory! <%s>", scriptsRoot));
    }//from w  w  w. j  a  va2  s .  co  m

    LOG.info("Preparing Shift Properties...");

    final Set<String> shiftKeysSet = npcIdShiftProperties.stringPropertyNames();
    final String[] shiftKeysArray = new String[shiftKeysSet.size()];
    shiftKeysSet.toArray(shiftKeysArray);
    final List<String> shiftKeys = Arrays.asList(shiftKeysArray);
    Collections.sort(shiftKeys, Collections.reverseOrder());

    if (shiftKeys.isEmpty()) {
        throw new RuntimeException("Error: Empty Shift Properties Detected!");
    }

    LOG.info(String.format("Searching: %s", scriptsRoot));

    final Iterator<File> luaFiles = FileUtils.iterateFiles(scriptsDirectory, extensions, true);

    while (luaFiles.hasNext()) {
        final File luaFile = luaFiles.next();
        updateFile(luaFile, shiftKeys, npcIdShiftProperties);
    }

    final StringBuilder elevatorSqlPathBuilder = new StringBuilder();
    elevatorSqlPathBuilder.append(configProperties.getProperty("darkstar_root", ""));
    elevatorSqlPathBuilder.append("sql/elevators.sql");

    final File elevatorFile = new File(elevatorSqlPathBuilder.toString());
    updateFile(elevatorFile, shiftKeys, npcIdShiftProperties);

    final StringBuilder transportSqlPathBuilder = new StringBuilder();
    transportSqlPathBuilder.append(configProperties.getProperty("darkstar_root", ""));
    transportSqlPathBuilder.append("sql/transport.sql");

    final File transportFile = new File(transportSqlPathBuilder.toString());
    updateFile(transportFile, shiftKeys, npcIdShiftProperties);

    LOG.info(String.format("Finished Updating Lua Scripts With <%d> Errors!", errors));
}