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:bigbank.transaction.ChainedTransactionManager.java

private <T> Iterable<T> reverse(Collection<T> collection) {
    List<T> list = new ArrayList<T>(collection);
    Collections.reverse(list);
    return list;/*from  ww w  .j a  va2 s.c  o m*/
}

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

/** Return a list of card ids for QUERY */
public ArrayList<HashMap<String, String>> findCardsForCardBrowser(String query, String _order,
        HashMap<String, String> deckNames) {
    String[] tokens = _tokenize(query);
    Pair<String, String[]> res1 = _where(tokens);
    String preds = res1.first;//  w  w  w  .  j  a  va  2 s .  com
    String[] args = res1.second;
    ArrayList<HashMap<String, String>> res = new ArrayList<HashMap<String, String>>();
    if (preds == null) {
        return res;
    }
    Pair<String, Boolean> res2 = _order(_order);
    String order = res2.first;
    boolean rev = res2.second;
    String sql = _query(preds, order, true);
    Cursor cur = null;
    try {
        cur = mCol.getDb().getDatabase().rawQuery(sql, args);
        while (cur.moveToNext()) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("id", cur.getString(0));
            map.put("sfld", cur.getString(1));
            map.put("deck", deckNames.get(cur.getString(2)));
            int queue = cur.getInt(3);
            String tags = cur.getString(4);
            map.put("flags", Integer.toString((queue == -1 ? 1 : 0) + (tags.matches(".*[Mm]arked.*") ? 2 : 0)));
            map.put("tags", tags);
            res.add(map);
        }
    } catch (SQLException e) {
        // invalid grouping
        Log.e(AnkiDroidApp.TAG, "Invalid grouping, sql: " + sql);
        return new ArrayList<HashMap<String, String>>();
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (rev) {
        Collections.reverse(res);
    }
    return res;
}

From source file:com.silverpeas.look.SilverpeasLook.java

/**
 * return the first space id with a specific CSS in path of given space
 * This space can be the given space itself or one of its parents
 * @param spaceId/*from www .j a v a2s .  co  m*/
 * @return the first space id (from given space to root) with a specific CSS. If no space
 * in path have got specific CSS, returns null.
 */
public String getSpaceWithCSS(String spaceId) {
    List<SpaceInst> path = organizationController.getSpacePath(spaceId);
    Collections.reverse(path);
    for (SpaceInst space : path) {
        String url = getSpaceCSSURL(space.getId());
        if (isDefined(url)) {
            return getShortSpaceId(space.getId());
        }
    }
    return null;
}

From source file:com.sfs.dao.GadgetPreferencesDAOImplTest.java

/**
 * Test of reorderGadgets method, of class GadgetPreferencesDAOImpl.
 *
 * @throws Exception the exception//w w w  .  j  a v a2 s  .co m
 */
@Test
public final void testReorderGadgets() throws Exception {
    System.out.println("reorderGadgets");

    GadgetsPreferencesBean gadgetsPreferences = this.gadgetPreferencesDAO.load(testUser.getDN());

    List<Integer> gadgetIdList = (List<Integer>) gadgetsPreferences.getOrderedGadgetIds();

    // Reverse the order of the Gadget IDs
    Collections.reverse(gadgetIdList);

    // Build the orderString
    String expResult = "";
    for (int gadgetId : gadgetIdList) {
        if (expResult.compareTo("") != 0) {
            expResult += ",";
        }
        expResult += String.valueOf(gadgetId);
    }

    GadgetsPreferencesBean reorderedGadgetsPreferences = this.gadgetPreferencesDAO
            .reorderGadgets(gadgetsPreferences, expResult);

    String result = "";

    Collection<Integer> reorderedGadgets = reorderedGadgetsPreferences.getOrderedGadgetIds();
    for (int gadgetId : reorderedGadgets) {
        if (result.compareTo("") != 0) {
            result += ",";
        }
        result += String.valueOf(gadgetId);
    }

    assertEquals(expResult, result);
}

From source file:com.nit.libanki.Finder.java

/** Return a list of card ids for QUERY */
public ArrayList<HashMap<String, String>> findCardsForCardBrowser(String query, String _order,
        HashMap<String, String> deckNames) {
    String[] tokens = _tokenize(query);
    Pair<String, String[]> res1 = _where(tokens);
    String preds = res1.first;//from w  ww . j av  a 2 s  .c  o m
    String[] args = res1.second;
    ArrayList<HashMap<String, String>> res = new ArrayList<HashMap<String, String>>();
    if (preds == null) {
        return res;
    }
    Pair<String, Boolean> res2 = _order(_order);
    String order = res2.first;
    boolean rev = res2.second;
    String sql = _query(preds, order, true);
    Cursor cur = null;
    cur = mCol.getDb().getDatabase().rawQuery(sql, args);

    try {
        cur = mCol.getDb().getDatabase().rawQuery(sql, args);
        while (cur.moveToNext()) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("id", cur.getString(0));
            map.put("sfld", cur.getString(1));
            map.put("deck", deckNames.get(cur.getString(2)));
            int queue = cur.getInt(3);
            String tags = cur.getString(4);
            map.put("flags", Integer.toString((queue == -1 ? 1 : 0) + (tags.matches(".*[Mm]arked.*") ? 2 : 0)));
            map.put("tags", tags);
            map.put("word", cur.getString(5));
            res.add(map);
        }
    } catch (SQLException e) {
        // invalid grouping
        Log.e(AnkiDroidApp.TAG, "Invalid grouping, sql: " + sql);
        return new ArrayList<HashMap<String, String>>();
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (rev) {
        Collections.reverse(res);
    }
    return res;
}

From source file:gobblin.data.management.copy.writer.FileAwareInputStreamDataWriter.java

/**
 * Sets the {@link FsPermission}, owner, group for the path passed. And recursively to all directories and files under
 * it./*from www.  j  a va 2 s .c  om*/
 */
private void setRecursivePermission(Path path, OwnerAndPermission ownerAndPermission) throws IOException {
    List<FileStatus> files = FileListUtils.listPathsRecursively(fs, path, FileListUtils.NO_OP_PATH_FILTER);

    // Set permissions bottom up. Permissions are set to files first and then directories
    Collections.reverse(files);

    for (FileStatus file : files) {
        setPathPermission(file.getPath(), addExecutePermissionsIfRequired(file, ownerAndPermission));
    }
}

From source file:com.seajas.search.contender.replication.TaxonomyCache.java

/**
 * Retrieve a list of IDs for a given match.
 * // w  ww . j av a2  s  .c om
 * @param match
 * @return List<Integer>
 */
public List<Integer> getIdsByMatch(final String match) {
    lock.readLock().lock();

    try {
        List<Integer> result = new ArrayList<Integer>();

        if (nodesByMatch.containsKey(match.trim().toLowerCase())) {
            TaxonomyNode node = nodesByMatch.get(match.trim().toLowerCase());

            do {
                result.add(node.getId());
            } while ((node = nodesById.get(node.getParentId())) != null);

            Collections.reverse(result);

            return result;
        } else
            return null;
    } finally {
        lock.readLock().unlock();
    }
}

From source file:forge.quest.QuestUtilUnlockSets.java

private static List<CardEdition> getUnlockableEditions(final QuestController qData) {
    if (qData.getFormat() == null || !qData.getFormat().canUnlockSets()) {
        return emptyEditions;
    }//from   w w  w  . j  a va  2  s . c o m

    if (qData.getUnlocksTokens() < 1) { // Should never happen if we made it this far but better safe than sorry...
        throw new RuntimeException("BUG? Could not find unlockable sets even though we should.");
    }
    List<CardEdition> options = new ArrayList<CardEdition>();

    // Sort current sets by date
    List<CardEdition> allowedSets = Lists.newArrayList(Iterables.transform(
            qData.getFormat().getAllowedSetCodes(), FModel.getMagicDb().getEditions().FN_EDITION_BY_CODE));
    Collections.sort(allowedSets);

    // Sort unlockable sets by date
    List<CardEdition> excludedSets = Lists.newArrayList(Iterables.transform(qData.getFormat().getLockedSets(),
            FModel.getMagicDb().getEditions().FN_EDITION_BY_CODE));
    Collections.sort(excludedSets);

    // get a number of sets between an excluded and any included set
    List<ImmutablePair<CardEdition, Long>> excludedWithDistances = new ArrayList<ImmutablePair<CardEdition, Long>>();
    for (CardEdition ex : excludedSets) {
        if (!unlockableSetTypes.contains(ex.getType())) // don't add non-traditional sets
            continue;
        long distance = Long.MAX_VALUE;
        for (CardEdition in : allowedSets) {
            long d = (Math.abs(ex.getDate().getTime() - in.getDate().getTime()));
            if (d < distance) {
                distance = d;
            }
        }
        excludedWithDistances.add(ImmutablePair.of(ex, distance));
    }

    // sort by distance, then by code desc
    Collections.sort(excludedWithDistances, new Comparator<ImmutablePair<CardEdition, Long>>() {
        @Override
        public int compare(ImmutablePair<CardEdition, Long> o1, ImmutablePair<CardEdition, Long> o2) {
            long delta = o2.right - o1.right;
            return delta < 0 ? -1 : delta == 0 ? 0 : 1;
        }
    });

    for (ImmutablePair<CardEdition, Long> set : excludedWithDistances) {
        options.add(set.left);
        // System.out.println("Padded with: " + fillers.get(i).getName());
    }
    Collections.reverse(options);

    return options.subList(0,
            Math.min(options.size(), Math.min(8, 2 + ((qData.getAchievements().getWin()) / 50))));
}

From source file:com.liferay.social.activity.test.util.BaseSocialActivityInterpreterTestCase.java

protected List<SocialActivity> getActivities() throws Exception {
    List<SocialActivity> activities = new ArrayList<>(SocialActivityLocalServiceUtil
            .getGroupActivities(group.getGroupId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS));

    Collections.reverse(activities);

    return activities;
}

From source file:de.tudarmstadt.ukp.csniper.webapp.search.xmi.SerializedCasContextProvider.java

@Override
public ItemContext getContext(EvaluationItem aItem, int aLeftSize, int aRightSize) throws IOException {
    Timer timer = new Timer();

    File base = new File(new File(corpusService.getRepositoryPath(), aItem.getCollectionId().toUpperCase()),
            BIN);/*from  w  ww.jav  a2 s  .c o m*/
    String docId = aItem.getDocumentId();
    JCasState state = jcasThreadLocal.get();
    if ((state.documentId == null) || (state.collectionId == null)
            || !StringUtils.equals(state.documentId, docId)
            || !StringUtils.equals(state.collectionId, aItem.getCollectionId())) {
        timer.start();

        ObjectInputStream is = null;
        try {
            // No need to reset the CAS
            is = new ObjectInputStream(
                    new XZCompressorInputStream(new FileInputStream(new File(base, docId + ".ser.xz"))));

            CASCompleteSerializer serializer = (CASCompleteSerializer) is.readObject();
            deserializeCASComplete(serializer, (CASImpl) state.cas);

            state.documentId = aItem.getDocumentId();
            state.collectionId = aItem.getCollectionId();
        } catch (IllegalStateException e) {
            throw new IOException(e);
        } catch (ClassNotFoundException e) {
            throw new IOException(e);
        } finally {
            closeQuietly(is);
        }

        timer.stop();
        log.debug("Reading the CAS took " + timer.getTime() + "ms");
    } else {
        log.debug("Reusing CAS");
    }

    timer.reset();
    timer.start();

    // text offset based
    String text = state.cas.getDocumentText();

    // Absolute offsets
    int windowBegin = Math.max(0, (int) aItem.getBeginOffset() - aLeftSize);
    int windowEnd = Math.min(text.length(), (int) aItem.getEndOffset() + aRightSize);

    // Relative offsets
    int unitBegin = (int) aItem.getBeginOffset() - windowBegin;
    int unitEnd = (int) aItem.getEndOffset() - windowBegin;

    StringBuilder windowText = new StringBuilder(text.substring(windowBegin, windowEnd));

    List<Token> tokens;
    try {
        tokens = JCasUtil.selectCovered(state.cas.getJCas(), Token.class, (int) aItem.getBeginOffset(),
                (int) aItem.getEndOffset());
    } catch (CASException e) {
        throw new IOException(e);
    }
    int unitEndDisplacement = 0;
    int matchEndDisplacement = 0;
    int matchBeginDisplacement = 0;

    boolean anyMatchSet = false;
    int matchBeginOffset = aItem.getOriginalTextMatchBegin();
    int matchEndOffset = aItem.getOriginalTextMatchEnd();

    if (aItem.isOriginalMatchSet()) {
        matchBeginOffset = aItem.getOriginalTextMatchBegin();
        matchEndOffset = aItem.getOriginalTextMatchEnd();
        anyMatchSet = true;
    } else if (aItem.isTokenMatchSet()) {
        matchBeginOffset = tokens.get(aItem.getTokenMatchBegin()).getBegin();
        matchEndOffset = tokens.get(aItem.getTokenMatchEnd()).getEnd();
        anyMatchSet = true;
    }

    Collections.reverse(tokens);
    // compute actual offsets if token based offsets are set
    if (outputPos) {
        for (Token t : tokens) {
            if (t.getPos() != null && t.getPos().getPosValue() != null) {
                String postfix = "/" + t.getPos().getPosValue();
                windowText.insert(t.getEnd() - windowBegin, postfix);
                unitEndDisplacement += postfix.length();
                if (anyMatchSet) {
                    if ((t.getEnd() <= matchEndOffset) && (t.getBegin() >= matchBeginOffset)) {
                        matchEndDisplacement += postfix.length();
                    }
                    if (t.getEnd() <= matchBeginOffset) {
                        matchBeginDisplacement += postfix.length();
                    }
                }
            }
        }
    }

    ItemContext ctx = new ItemContext(windowText.toString(), windowBegin, windowEnd, unitBegin,
            unitEnd + unitEndDisplacement);

    if (anyMatchSet) {
        ctx.setMatch(matchBeginOffset - windowBegin + matchBeginDisplacement,
                matchEndOffset - windowBegin + matchBeginDisplacement + matchEndDisplacement);
    }

    ctx.setTextLength(text.length());

    timer.stop();
    log.debug("Extracting the context took " + timer.getTime() + "ms");

    return ctx;
}