Example usage for java.util Collections reverse

List of usage examples for java.util Collections reverse

Introduction

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

Prototype

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void reverse(List<?> list) 

Source Link

Document

Reverses the order of the elements in the specified list.

This method runs in linear time.

Usage

From source file:com.cloudant.mazha.BulkAPITest.java

List<String> createRevisionList(Response res, int num) {
    List<String> revs = new ArrayList<String>();
    String currentRev = res.getRev();
    revs.add(currentRev);/*from  ww w  . j  a  v  a2 s .c o m*/
    for (int i = 0; i < num; i++) {
        currentRev = CouchUtils.generateNextRevisionId(currentRev);
        revs.add(currentRev);
    }
    // it is important the list is in reverse order
    Collections.reverse(revs);
    return revs;
}

From source file:com.hichinaschool.flashcards.libanki.Finder.java

/** Return a list of card ids for QUERY */
public List<Long> findCards(String query, String _order) {
    String[] tokens = _tokenize(query);
    Pair<String, String[]> res1 = _where(tokens);
    String preds = res1.first;/*from w w w  .j  av a 2  s. c  om*/
    String[] args = res1.second;
    List<Long> res = new ArrayList<Long>();
    if (preds == null) {
        return res;
    }
    Pair<String, Boolean> res2 = _order(_order);
    String order = res2.first;
    boolean rev = res2.second;
    String sql = _query(preds, order, false);
    Cursor cur = null;
    try {
        cur = mCol.getDb().getDatabase().rawQuery(sql, args);
        while (cur.moveToNext()) {
            res.add(cur.getLong(0));
        }
    } catch (SQLException e) {
        // invalid grouping
        return new ArrayList<Long>();
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (rev) {
        Collections.reverse(res);
    }
    return res;
}

From source file:net.dv8tion.jda.core.requests.restaction.order.RoleOrderAction.java

@Override
protected RequestBody finalizeData() {
    final Member self = guild.getSelfMember();
    final boolean isOwner = self.isOwner();

    if (!isOwner) {
        if (self.getRoles().isEmpty())
            throw new IllegalStateException(
                    "Cannot move roles above your highest role unless you are the guild owner");
        if (!self.hasPermission(Permission.MANAGE_ROLES))
            throw new PermissionException(Permission.MANAGE_ROLES);
    }//from  ww  w.  j  av  a  2s  . c  om

    JSONArray array = new JSONArray();
    List<Role> ordering = new ArrayList<>(orderList);

    //If not in normal discord order, reverse.
    // Normal order is descending, not ascending.
    if (ascendingOrder)
        Collections.reverse(ordering);

    for (int i = 0; i < ordering.size(); i++) {
        Role role = ordering.get(i);
        final int initialPos = role.getPosition();
        if (initialPos != i && !isOwner && !self.canInteract(role))
            // If the current role was moved, we are not owner and we can't interact with the role then throw a PermissionException
            throw new IllegalStateException(
                    "Cannot change order: One of the roles could not be moved due to hierarchical power!");

        array.put(new JSONObject().put("id", role.getId()).put("position", i + 1)); //plus 1 because position 0 is the @everyone position.
    }

    return getRequestBody(array);
}

From source file:com.intellij.lang.jsgraphql.endpoint.doc.psi.JSGraphQLEndpointDocPsiUtil.java

/**
 * Gets the text of the continuous comments placed directly above the specified element
 * @param element element whose previous siblings are enumerated and included if they're documentation comments
 * @return the combined text of the documentation comments, preserving line breaks, or <code>null</code> if no documentation is available
 *//*from  ww  w . ja  v a2s  . c o m*/
public static String getDocumentation(PsiElement element) {
    final PsiComment comment = PsiTreeUtil.getPrevSiblingOfType(element, PsiComment.class);
    if (isDocumentationComment(comment)) {
        final List<PsiComment> siblings = Lists.newArrayList(comment);
        getDocumentationCommentSiblings(comment, siblings, PsiElement::getPrevSibling);
        Collections.reverse(siblings);
        return siblings.stream().map(c -> StringUtils.stripStart(c.getText(), "# "))
                .collect(Collectors.joining("\n"));
    }
    return null;
}

From source file:com.romeikat.datamessie.core.base.util.publishedDates.PublishedDateStrategy.java

private List<LocalDate> getPublishedDatesForProcessing(final SharedSessionContract ssc,
        final DocumentsFilterSettings dfs) {
    final LocalDate fromDate = dfs.getFromDate();
    final LocalDate toDate = dfs.getToDate();
    // Both dates provided => all dates in range (descending)
    if (fromDate != null && toDate != null) {
        return DateUtil.getLocalDatesBetween(toDate, fromDate);
    }/*  ww  w  .  j  a  v  a 2 s . co  m*/
    // Otherwise => all published dates that actually exist (descending)
    else {
        final Set<LocalDate> allPublishedDates = getAllPublishedDates(ssc);
        final Predicate<LocalDate> publishedDatePredicate = new Predicate<LocalDate>() {
            @Override
            public boolean apply(final LocalDate publishedDate) {
                final boolean fromDateMatch = fromDate == null || publishedDate.compareTo(fromDate) >= 0;
                final boolean toDateMatch = toDate == null || publishedDate.compareTo(toDate) <= 0;
                return fromDateMatch && toDateMatch;
            }
        };
        final Collection<LocalDate> publishedDates = Collections2.filter(allPublishedDates,
                publishedDatePredicate);
        // Sort descending
        final List<LocalDate> publishedDatesSorted = Lists.newArrayList(publishedDates);
        Collections.sort(publishedDatesSorted);
        Collections.reverse(publishedDatesSorted);
        // Done
        return publishedDatesSorted;
    }
}

From source file:fr.univrouen.poste.utils.ConfigInterceptor.java

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {

    // we want to add usual model in modelAndView only when needed, ie with
    // direct html view :
    // not for download response (for example) because we don't need it
    // not for redirect view because we don't need it and we don't want that
    // they appears in the url

    if (modelAndView != null && modelAndView.hasView()) {

        boolean isViewObject = modelAndView.getView() == null;

        boolean isRedirectView = !isViewObject && modelAndView.getView() instanceof RedirectView;

        boolean viewNameStartsWithRedirect = isViewObject
                && modelAndView.getViewName().startsWith(UrlBasedViewResolver.REDIRECT_URL_PREFIX);

        if (!isRedirectView && !viewNameStartsWithRedirect) {

            String title = AppliConfig.getCacheTitre();
            modelAndView.addObject("title", title);

            String piedPage = AppliConfig.getCachePiedPage();
            modelAndView.addObject("piedPage", piedPage);

            String imageUrl = AppliConfig.getCacheImageUrl();
            modelAndView.addObject("imageUrl", imageUrl);

            String path = request.getServletPath();
            String subTitle = subTitles.get(path);
            String activeMenu = path.replaceAll("/", "");

            if (subTitle == null) {
                List<String> keys = new Vector<String>(subTitles.keySet());
                Collections.reverse(keys);
                for (String key : keys) {
                    if (path.startsWith(key)) {
                        subTitle = subTitles.get(key);
                        ;//ww w .ja v a 2s . c  o  m
                        activeMenu = key.replaceAll("/", "");
                        break;
                    }
                }
            }

            modelAndView.addObject("subTitle", subTitle);
            modelAndView.addObject("activeMenu", activeMenu);

            modelAndView.addObject("candidatCanSignup", AppliConfig.getCacheCandidatCanSignup());

            modelAndView.addObject("versionEsupDematEC", AppliVersion.getCacheVersion());

        }

        if (request.getParameter("size") != null) {
            Integer size = Integer.valueOf(request.getParameter("size"));
            request.getSession().setAttribute("size_in_session", size);
        } else if (request.getSession(false) != null
                && request.getSession().getAttribute("size_in_session") == null) {
            request.getSession().setAttribute("size_in_session", new Integer(40));
        }

    }
}

From source file:com.asual.summer.core.resource.PropertyResource.java

public void setWildcardLocations(String[] locations) {

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    List<Resource[]> resourceLocations = new ArrayList<Resource[]>();

    List<Resource> fileResources = new ArrayList<Resource>();
    List<Resource> jarResources = new ArrayList<Resource>();

    for (String location : locations) {
        try {//from   w w w  .ja  v  a 2  s  .  co  m
            Resource[] wildcard = resolver.getResources(location);
            if (wildcard != null && wildcard.length > 0) {
                resourceLocations.add(wildcard);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    int i = 0;
    boolean entries = true;

    while (entries) {
        entries = false;
        for (Resource[] location : resourceLocations) {
            if (location.length > i) {
                try {
                    boolean isJar = ResourceUtils.isJarURL(location[i].getURL());
                    if (isJar) {
                        jarResources.add(location[i]);
                    } else {
                        fileResources.add(location[i]);
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
                entries = true;
            }
        }
        i++;
    }

    fileResources.addAll(jarResources);
    Collections.reverse(fileResources);

    this.resources = fileResources.toArray(new Resource[fileResources.size()]);
}

From source file:me.childintime.childintime.InitialSetup.java

/**
 * Clean and refresh the application environment for developers.
 * This deletes all application files and configurations from previous versions.
 * This ensures that a fresh application instance is used for development.
 *//*from w  w  w . j  a v  a2s  .c  o  m*/
private void cleanApplicationEnvironment() {
    // Show a status message
    this.progressDialog.setStatus("Confirming environment cleanup...");

    // Make sure the clean environment feature is enabled
    if (!App.APP_CLEAN_ENVIRONMENT)
        return;

    // Show a warning
    if (!Arrays.asList(Core.getInstance().getStarupArgs()).contains(FLAG_HIDE_CLEAN_ENVIRONMENT_WARNING)) {
        // Create a list with the buttons to show in the option dialog
        List<String> buttons = new ArrayList<>();
        buttons.add("Clean Environment");
        buttons.add("Keep Environment");

        // Reverse the button list if we're on a Mac OS X system
        if (Platform.isMacOsX())
            Collections.reverse(buttons);

        // Show the option dialog
        final int option = JOptionPane.showOptionDialog(this.progressDialog,
                "The developer option Clean Environment is enabled.\n\n"
                        + "Would you like to clean your application environment?\n\n"
                        + "Cleaning the environment will delete all previous application files and configurations,\n"
                        + "to ensure that you're using a fresh application instance for development.\n\n"
                        + "This feature must be disabled in production.",
                App.APP_NAME + " - Developer mode - Environment cleanup", JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE, null, buttons.toArray(),
                buttons.get(!Platform.isMacOsX() ? 0 : 1));

        // Make sure the clean option is pressed
        if (option != (!Platform.isMacOsX() ? 0 : 1))
            return;
    }

    // Show a status message
    this.progressDialog.setStatus("Refreshing application environment...");

    // Delete the application directory
    try {
        if (App.getDirectory().exists())
            FileUtils.deleteDirectory(App.getDirectory());

    } catch (IOException e) {
        showError("Failed to refresh application environment.");
        e.printStackTrace();
    }
}

From source file:org.obiba.onyx.engine.ActionDefinitionConfiguration.java

/**
 * Returns an array of hierarchical codes that are used to find an associated {@code ActionDefinition} instance. This
 * method will build an array of codes with the first element being the most specific:
 * <ul>/*from  ww  w . j a  va 2 s. c  o  m*/
 * <li>ACTION_PREFIX.type.stateName.module.stage</li>
 * <li>ACTION_PREFIX.type.stateName.module</li>
 * <li>ACTION_PREFIX.type.stateName</li>
 * <li>ACTION_PREFIX.type</li>
 * <li>ACTION_PREFIX
 * <li>
 * </ul>
 * @param type the {@link ActionType} of the {@code ActionDefinition}
 * @param stateName the name of the state on which the action is performed
 * @param module the module that contributed the stage
 * @param stage the stage on which the action is performed
 * @return an array of codes
 */
static public String[] calculateCodes(ActionType type, String stateName, String module, String stage) {
    ArrayList<String> codes = new ArrayList<String>();
    StringBuilder sb = new StringBuilder(ACTION_PREFIX);
    codes.add(sb.toString());
    sb.append(SEPARATOR).append(type);
    codes.add(sb.toString());
    if (stateName != null) {
        sb.append(SEPARATOR).append(stateName);
        codes.add(sb.toString());
    }
    if (module != null) {
        sb.append(SEPARATOR).append(module);
        codes.add(sb.toString());
    }
    if (stage != null) {
        sb.append(SEPARATOR).append(stage);
        codes.add(sb.toString());
    }
    Collections.reverse(codes);
    return codes.toArray(new String[codes.size()]);
}

From source file:org.wallerlab.yoink.cube.service.VoronoiCalculator.java

private void getTwoClosestNeighbours(List<Atom> twoNeighbours, List<Double> neighbourDistances, Atom atom,
        double distance, List<Molecule> twoMolecules, Molecule molecule) {
    int size = neighbourDistances.size();
    switch (size) {
    case 0:/*from   w  ww . j  a v a2  s.  com*/
        // add one neighbour
        neighbourDistances.add(0, distance);
        twoNeighbours.add(0, atom);
        twoMolecules.add(0, molecule);
        break;
    case 1:
        // add one more neighbour.the first neighbour is the closer one
        neighbourDistances.add(1, distance);
        twoNeighbours.add(1, atom);
        twoMolecules.add(1, molecule);
        if (neighbourDistances.get(0) >= neighbourDistances.get(1)) {
            Collections.reverse(neighbourDistances);
            Collections.reverse(twoNeighbours);
            Collections.reverse(twoMolecules);
        }
        break;
    case 2:// compare current distance with the distance of second
           // neighbour, if true, replace second neighbor and compare with
           // the first neighbour
        if (neighbourDistances.get(1) >= distance) {
            neighbourDistances.set(1, distance);
            twoNeighbours.set(1, atom);
            twoMolecules.set(1, molecule);
            if (neighbourDistances.get(0) >= neighbourDistances.get(1)) {
                Collections.reverse(neighbourDistances);
                Collections.reverse(twoNeighbours);
                Collections.reverse(twoMolecules);
            }
        }
        break;
    default:
        throw new IllegalArgumentException("Invalid type of size: " + size);
    }
}