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:es.uniovi.imovil.fcrtrainer.HighscoresFragment.java

private void initializeListView(int selectedExerciseId) {
    mHighscoreListView = (ListView) mRootView.findViewById(R.id.list_view_highscores);

    if (firstTime()) {
        addBasicHighscores();/*from   ww  w .  jav a2 s. co m*/
    }

    ArrayList<Highscore> highscores = loadHighscores();

    highscores = selectHighscores(highscores, selectedExerciseId);

    Collections.sort(highscores);
    Collections.reverse(highscores);

    HighscoreAdapter adapter = new HighscoreAdapter(getActivity(), highscores);
    mHighscoreListView.setAdapter(adapter);
}

From source file:com.sillelien.dollar.api.types.DollarList.java

@NotNull
@Override/*from  ww  w.  j a v  a  2s.com*/
@Guarded(NotNullGuard.class)
public var $negate() {
    ArrayList<var> result = new ArrayList<>(list.mutable());
    Collections.reverse(result);
    return DollarFactory.fromValue(result, errors());
}

From source file:Main.java

private static ArrayList<ArrayList> sortObjectArrayListSimpleMaster(ArrayList listIn, String paramName) {
    ArrayList<ArrayList> answer = new ArrayList<ArrayList>();
    ArrayList newList = new ArrayList();
    ArrayList<Integer> indices = new ArrayList<Integer>();
    try {//from  w  ww . j a  v  a  2  s.  c  o  m
        if (listIn.size() > 0) {
            Class<?> c = listIn.get(0).getClass();
            Field f = c.getDeclaredField(paramName);
            f.setAccessible(true);
            Class<?> t = f.getType();
            Double dd = new Double(14);
            Float ff = new Float(14);
            Integer ii = new Integer(14);
            Map sortedPos = new LinkedHashMap();
            Map sortedNeg = new LinkedHashMap();
            Map unsorted = new LinkedHashMap();
            int indexCount = 0;
            long count = 0;
            if (t.isPrimitive()) {
                for (Object thisObj : listIn) {
                    Object o = f.get(thisObj);
                    double d = 0;
                    if (t.getName().equals("char")) {
                        d = (int) ((Character) o);
                    } else if (t.isInstance(dd))
                        d = (Double) o;
                    else if (t.isInstance(ff))
                        d = (Float) o;
                    else if (t.isInstance(ii))
                        d = (Integer) o;
                    else
                        d = new Double(o.toString());

                    boolean isNegative = false;

                    if (d < 0) {
                        isNegative = true;
                        d = Math.abs(d);
                    }

                    String format = "%1$30f";
                    String newKey = String.format(format, d);
                    String format2 = "%1$20d";
                    String countString = String.format(format2, count);
                    newKey += "-" + countString;
                    if (isNegative) {
                        sortedNeg.put(newKey, thisObj);
                    } else {
                        sortedPos.put(newKey, thisObj);
                    }
                    unsorted.put(thisObj, indexCount);
                    count++;
                    indexCount++;
                }
                TreeMap<String, Object> resultPos = new TreeMap();
                resultPos.putAll(sortedPos);
                sortedPos = resultPos;
                TreeMap<String, Object> resultNeg = new TreeMap();
                resultNeg.putAll(sortedNeg);
                sortedNeg = resultNeg;
            } else if (t.isInstance(paramName)) {
                // System.out.println("is a string with value " + o);
                for (Object thisObj : listIn) {
                    String key = (String) (f.get(thisObj));
                    sortedPos.put(key + "-" + count, thisObj);
                    unsorted.put(thisObj, indexCount);
                    count++;
                    indexCount++;
                }
                TreeMap<String, Object> result = new TreeMap(String.CASE_INSENSITIVE_ORDER);
                result.putAll(sortedPos);
                sortedPos = result;
            }

            Iterator itNeg = sortedNeg.entrySet().iterator();
            while (itNeg.hasNext()) {
                Map.Entry pairs = (Map.Entry) itNeg.next();
                newList.add(pairs.getValue());
                itNeg.remove();
            }

            Collections.reverse(newList);

            Iterator itPos = sortedPos.entrySet().iterator();
            while (itPos.hasNext()) {
                Map.Entry pairs = (Map.Entry) itPos.next();
                Object obj = pairs.getValue();
                newList.add(obj);
                indices.add((Integer) unsorted.get(obj));
                itPos.remove();
            }
        }
    } catch (Exception e) {
        System.out
                .println("problem sorting list.  listIn.size(): " + listIn.size() + " and param: " + paramName);
        answer.add(newList);
        answer.add(indices);
        return answer;
    }
    answer.add(newList);
    answer.add(indices);
    return answer;
}

From source file:annis.gui.docbrowser.DocBrowserTable.java

/**
 * Updates the table with docnames and generate the additional columns defined
 * by the user.//  ww w  .java 2s. c om
 *
 * @param docs the list of documents, wrapped in the {@link Annotation} POJO
 */
void setDocNames(List<Annotation> docs) {

    container = new IndexedContainer();

    container.addContainerProperty("document name", String.class, "n/a");
    MetaColumns metaCols = generateMetaColumns();

    for (MetaDataCol metaDatum : metaCols.visibleColumns) {
        container.addContainerProperty(metaDatum.getColName(), String.class, "n/a");
    }

    for (MetaDataCol metaDatum : metaCols.sortColumns) {
        container.addContainerProperty(metaDatum.getColName(), String.class, "n/a");
    }

    container.addContainerProperty("corpus path", String.class, "n/a");
    container.addContainerProperty("info", Button.class, null);
    container.addContainerProperty("visualizer", Panel.class, null);

    for (Annotation a : docs) {
        String doc = a.getName();

        // reverse path and delete the brackets and set a new separator:
        // corpus > ... > subcorpus > document
        List<String> pathList = a.getAnnotationPath();
        if (pathList == null) {
            pathList = new LinkedList<>();
        }

        Collections.reverse(pathList);
        String path = StringUtils.join(pathList, " > ");

        // use corpus path for row id, since it should be unique by annis db schema
        Item row = container.addItem(path);
        if (row != null) {
            row.getItemProperty("document name").setValue(doc);

            // add the metadata columns.
            for (MetaDataCol metaDataCol : metaCols.visibleColumns) {
                String value = generateCell(a.getAnnotationPath(), metaDataCol);
                row.getItemProperty(metaDataCol.getColName()).setValue(value);
            }

            for (MetaDataCol metaDataCol : metaCols.sortColumns) {
                if (!metaCols.visibleColumns.contains(metaDataCol)) {
                    // corpusName() holds the corpus path
                    String value = generateCell(a.getAnnotationPath(), metaDataCol);
                    row.getItemProperty(metaDataCol.getColName()).setValue(value);
                }
            }

            row.getItemProperty("corpus path").setValue(path);
            row.getItemProperty("visualizer").setValue(generateVisualizerLinks(doc));
            row.getItemProperty("info").setValue(generateInfoButtonCell(doc));
        }
    }

    setContainerDataSource(container);
    Object[] metaDataColNames = new Object[metaCols.visibleColumns.size()];

    for (int i = 0; i < metaDataColNames.length; i++) {
        metaDataColNames[i] = metaCols.visibleColumns.get(i).getColName();
    }

    Object[] columnNames = ArrayUtils.addAll(
            ArrayUtils.addAll(new Object[] { "document name" }, metaDataColNames),
            new Object[] { "corpus path", "visualizer", "info" });

    setVisibleColumns(columnNames);

    for (Object colName : columnNames) {
        setColumnHeader((String) colName, (String) colName);
    }

    sortByMetaData(metaCols.sortColumns);
}

From source file:com.ibm.appscan.bamboo.plugin.impl.SASTScanner.java

private String getLastLogEntry(TaskContext taskContext) {

    List<LogEntry> logs = taskContext.getBuildLogger().getLastNLogEntries(2);
    Collections.reverse(logs);

    String text = ""; //$NON-NLS-1$

    for (LogEntry log : logs) {
        text = log.getUnstyledLog();//www.  j a va  2  s.  c  om
        if (!text.trim().isEmpty())
            break;
    }

    return text;
}

From source file:de.alpharogroup.lang.object.CompareObjectExtensionsTest.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(enabled = true)//from  www  .  ja va2  s  .  c  om
public void testCompareTo() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    final List<Person> persons = new ArrayList<>();
    final Person obelix = new Person();
    obelix.setGender(Gender.MALE);
    obelix.setName("obelix");

    final Person asterix = new Person();
    asterix.setGender(Gender.MALE);
    asterix.setName("asterix");

    final Person miraculix = new Person();
    miraculix.setGender(Gender.MALE);
    miraculix.setName("miraculix");

    final int i = CompareObjectExtensions.compareTo(asterix, obelix, "name");

    System.out.println(i);

    persons.add(obelix);
    persons.add(asterix);
    persons.add(miraculix);
    System.out.println("Unsorted Persons:");
    System.out.println(persons.toString());
    final Comparator defaultComparator = new BeanComparator("name");
    Collections.sort(persons, defaultComparator);
    System.out.println("Sorted Persons by name:");
    System.out.println(persons.toString());
    Collections.reverse(persons);
    System.out.println("Sorted Persons by name reversed:");
    System.out.println(persons.toString());
}

From source file:com.predic8.membrane.core.interceptor.administration.AdminRESTInterceptor.java

@Mapping("/admin/rest/proxies(/?\\?.*)?")
public Response getProxies(final QueryParameter params, String relativeRootPath) throws Exception {
    final List<AbstractServiceProxy> proxies = getServiceProxies();

    if ("order".equals(params.getString("sort"))) {
        if (params.getString("order", "asc").equals("desc"))
            Collections.reverse(proxies);
    } else {/*ww  w. j a  va 2  s  .  c  o m*/
        Collections.sort(proxies, ComparatorFactory.getAbstractServiceProxyComparator(
                params.getString("sort", "name"), params.getString("order", "asc")));
    }

    final int offset = params.getInt("offset", 0);
    int max = params.getInt("max", proxies.size());

    final List<AbstractServiceProxy> paginated = proxies.subList(offset,
            Math.min(offset + max, proxies.size()));

    return json(new JSONContent() {
        public void write(JsonGenerator gen) throws Exception {
            gen.writeStartObject();
            gen.writeArrayFieldStart("proxies");
            int i = offset;
            if (params.getString("order", "asc").equals("desc"))
                i = proxies.size() - i + 1;
            for (AbstractServiceProxy p : paginated) {
                gen.writeStartObject();
                gen.writeNumberField("order", i += params.getString("order", "asc").equals("desc") ? -1 : 1);
                gen.writeStringField("name", p.toString());
                gen.writeBooleanField("active", p.isActive());
                if (!p.isActive())
                    gen.writeStringField("error", p.getErrorState());
                gen.writeNumberField("listenPort", p.getKey().getPort());
                gen.writeStringField("virtualHost", p.getKey().getHost());
                gen.writeStringField("method", p.getKey().getMethod());
                gen.writeStringField("path", p.getKey().getPath());
                gen.writeStringField("targetHost", p.getTargetHost());
                gen.writeNumberField("targetPort", p.getTargetPort());
                gen.writeNumberField("count", p.getCount());
                gen.writeObjectFieldStart("actions");
                if (!isReadOnly()) {
                    gen.writeStringField("delete", "/admin/service-proxy/delete?name="
                            + URLEncoder.encode(RuleUtil.getRuleIdentifier(p), "UTF-8"));
                }
                if (!p.isActive())
                    gen.writeStringField("start", "/admin/service-proxy/start?name="
                            + URLEncoder.encode(RuleUtil.getRuleIdentifier(p), "UTF-8"));
                gen.writeEndObject();
                gen.writeEndObject();
            }
            gen.writeEndArray();
            gen.writeNumberField("total", proxies.size());
            gen.writeEndObject();
        }
    });
}

From source file:com.nimbits.server.process.BlobStoreImpl.java

@Override
public List<Value> getSeries(final ValueService valueService, final Entity entity,
        final Optional<Range<Date>> timespan, final Optional<Range<Integer>> range,
        final Optional<String> mask) {
    //TODO - some way to test if a count has been reached before reading all files if no timespan is give - like test the list by processing it to see if it's complete
    //enough to return while reading other files.
    String root = settingsService.getSetting(ServerSetting.storeDirectory);
    String path = root + "/" + entity.getKey();
    List<Value> allvalues = new ArrayList<>(INITIAL_CAPACITY);
    List<String> allReadFiles = new ArrayList<>(INITIAL_CAPACITY);
    File file = new File(path);

    Range<Date> maxRange = timespan.isPresent()
            ? Range.closed(defragmenter.zeroOutDateToStart(timespan.get().lowerEndpoint()),
                    defragmenter.zeroOutDateToStart(timespan.get().upperEndpoint()))
            : Range.closed(defragmenter.zeroOutDateToStart(new Date(0)),
                    defragmenter.zeroOutDateToStart(new Date())); // all dates

    if (file.exists()) {

        List<String> dailyFolderPaths = new ArrayList<>();

        for (String dailyFolderPath : file.list()) {

            File node = new File(dailyFolderPath);

            if (!node.getName().endsWith(SNAPSHOT)) {
                Long timestamp = Long.valueOf(dailyFolderPath);
                if (maxRange.contains(new Date(timestamp))) {

                    dailyFolderPaths.add(root + "/" + entity.getKey() + "/" + dailyFolderPath);
                }//  ww w  .jav  a 2  s  .com

            }

        }

        if (!dailyFolderPaths.isEmpty()) {
            Collections.sort(dailyFolderPaths);
            Collections.reverse(dailyFolderPaths);

            for (String sortedDayPath : dailyFolderPaths) {
                Iterator result2 = FileUtils.iterateFiles(new File(sortedDayPath), null, false);
                List<String> filePaths = new ArrayList<>();

                while (result2.hasNext()) {

                    File listItem = (File) result2.next();
                    String filePath = listItem.getName();
                    if (!filePath.endsWith(SNAPSHOT)) {
                        filePaths.add(sortedDayPath + "/" + filePath);
                    }

                }
                Collections.sort(filePaths);
                Collections.reverse(filePaths);

                for (String sortedFilePath : filePaths) {
                    List<Value> values = readValuesFromFile(sortedFilePath);
                    allvalues.addAll(values);
                    allReadFiles.add(sortedFilePath);

                }

            }
        }

        List<Value> filtered = storageIO.filterValues(allvalues, timespan, range, mask);

        if (allReadFiles.size() > INITIAL_CAPACITY) { //TODO will break if # of days = initial capacity
            //   logger.info("Defragmenting " + allReadFiles.size());
            deleteAndRestore(this, valueService, entity, allvalues, allReadFiles);
        }
        //  logger.info("****** returning " + filtered.size());
        return ImmutableList.copyOf(filtered);
    } else {
        logger.info("file not found");
        return Collections.emptyList();
    }

}

From source file:ch.cyberduck.core.b2.B2LargeUploadPartService.java

/**
 * @param file File reference//w w  w .  j  a  v  a 2s .c om
 * @return File id of unfinished large upload
 */
public List<B2FileInfoResponse> find(final Path file) throws BackgroundException {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Finding multipart uploads for %s", file));
    }
    try {
        final List<B2FileInfoResponse> uploads = new ArrayList<B2FileInfoResponse>();
        // This operation lists in-progress multipart uploads. An in-progress multipart upload is a
        // multipart upload that has been initiated, using the Initiate Multipart Upload request, but has
        // not yet been completed or aborted.
        String startFileId = null;
        do {
            final B2ListFilesResponse chunk;
            chunk = session.getClient()
                    .listUnfinishedLargeFiles(new B2FileidProvider(session)
                            .getFileid(containerService.getContainer(file), new DisabledListProgressListener()),
                            startFileId, null);
            for (B2FileInfoResponse upload : chunk.getFiles()) {
                if (file.isDirectory()) {
                    final Path parent = new Path(containerService.getContainer(file), upload.getFileName(),
                            EnumSet.of(Path.Type.file)).getParent();
                    if (parent.equals(file)) {
                        uploads.add(upload);
                    }
                } else {
                    if (StringUtils.equals(upload.getFileName(), containerService.getKey(file))) {
                        uploads.add(upload);
                    }
                }
            }
            if (log.isInfoEnabled()) {
                log.info(String.format("Found %d previous multipart uploads for %s", uploads.size(), file));
            }
            startFileId = chunk.getNextFileId();
        } while (startFileId != null);
        if (log.isInfoEnabled()) {
            for (B2FileInfoResponse upload : uploads) {
                log.info(String.format("Found multipart upload %s for %s", upload, file));
            }
        }
        // Uploads are listed in the order they were started, with the oldest one first
        Collections.sort(uploads, new Comparator<B2FileInfoResponse>() {
            @Override
            public int compare(final B2FileInfoResponse o1, final B2FileInfoResponse o2) {
                return o1.getUploadTimestamp().compareTo(o2.getUploadTimestamp());
            }
        });
        Collections.reverse(uploads);
        return uploads;
    } catch (B2ApiException e) {
        throw new B2ExceptionMappingService().map("Upload {0} failed", e, file);
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map("Cannot delete {0}", e, file);
    }
}

From source file:com.lyncode.jtwig.functions.builtin.ListFunctions.java

@JtwigFunction(name = "reverse")
public List reverse(@Parameter Object input) {
    ObjectIterator objectIterator = new ObjectIterator(input);
    List<Object> result = new ArrayList<Object>();
    while (objectIterator.hasNext())
        result.add(objectIterator.next());

    Collections.reverse(result);
    return result;
}