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:it.zielke.a2pdf.Anki2PDF.java

private List<String> reorderPages(List<String> sideContent) {
    LinkedList<String> ret = new LinkedList<String>();
    int rowsize = settings.getRowSize();
    for (int i = 0; i < sideContent.size(); i += rowsize) {
        List<String> tmp = sideContent.subList(i, Math.min(i + rowsize, sideContent.size()));
        Collections.reverse(tmp);
        ret.addAll(tmp);//from w w w.  j a  v a  2 s  . co  m
    }
    return ret;
}

From source file:com.cronutils.model.time.TimeNode.java

/**
 * We return same reference value if matches or previous one if does not match.
 * Then we start applying shifts./*from  w  w  w  .  j a  v a2 s  .  c  o m*/
 * This way we ensure same value is returned if no shift is requested.
 * @param reference - reference value
 * @param shiftsToApply - shifts to apply
 * @return NearestValue instance, never null. Holds information on nearest (backward) value and shifts performed.
 */
@VisibleForTesting
NearestValue getNearestBackwardValue(int reference, int shiftsToApply) {
    List<Integer> values = new ArrayList<Integer>(this.values);
    Collections.reverse(values);
    int index = 0;
    boolean foundSmaller = false;
    AtomicInteger shift = new AtomicInteger(0);
    if (!values.contains(reference)) {
        for (Integer value : values) {
            if (value < reference) {
                index = values.indexOf(value);
                shiftsToApply--;//we just moved a position!
                foundSmaller = true;
                break;
            }
        }
        if (!foundSmaller) {
            shift.incrementAndGet();
        }
    } else {
        index = values.indexOf(reference);
    }
    int value = values.get(index);
    for (int j = 0; j < shiftsToApply; j++) {
        value = getValueFromList(values, index + 1, shift);
        index = values.indexOf(value);
    }
    return new NearestValue(value, shift.get());
}

From source file:de.codesourcery.jasm16.compiler.Main.java

private int run(String[] args) throws Exception {
    final List<ICompilationUnit> units = new ArrayList<ICompilationUnit>();

    final Stack<String> arguments = new Stack<String>();
    for (String arg : args) {
        arguments.push(arg);/*from w  ww . j  ava2 s. c  o  m*/
    }
    Collections.reverse(arguments);

    while (!arguments.isEmpty()) {
        final String arg = arguments.peek();
        if (arg.startsWith("-") || arg.startsWith("--")) {
            try {
                handleCommandlineOption(arg, arguments);
            } catch (NoSuchElementException e) {
                printError("Invalid command line, option " + arg + " lacks argument.");
                return 1;
            }
        } else {
            units.add(createCompilationUnit(arguments.pop()));
        }
    }

    if (verboseOutput) {
        printVersionInfo();
    }

    if (units.isEmpty()) {
        printError("No input files.");
        return 1;
    }

    setupCompiler(units);

    final ICompilationListener listener;
    if (printDebugStats || verboseOutput) {
        listener = new DebugCompilationListener(printDebugStats);
    } else {
        listener = new CompilationListener();
    }

    if (printSourceCode) {
        compiler.insertCompilerPhaseAfter(new CompilerPhase("format-code") {
            @Override
            protected void run(ICompilationUnit unit, ICompilationContext context) throws IOException {
                if (unit.getAST() != null) {
                    ASTUtils.visitInOrder(unit.getAST(), new FormattingVisitor(context));
                }
            };

        }, ICompilerPhase.PHASE_GENERATE_CODE);
    }

    // invoke compiler
    compiler.compile(units, listener);

    boolean hasErrors = false;
    for (ICompilationUnit unit : units) {
        if (unit.hasErrors()) {
            Misc.printCompilationErrors(unit, Misc.readSource(unit), printStackTraces);
            hasErrors = true;
        }
    }

    if (dumpObjectCode) {
        dumpObjectCode();
    }
    return hasErrors ? 1 : 0;
}

From source file:it.iit.genomics.cru.simsearch.bundle.utils.AnnotationsFromTrack.java

public Collection<String> getAnnotationsByNumberOfOverlap() {
    ArrayList<Integer> counts = new ArrayList<>();
    counts.addAll(annotationsMappedCount.values());
    Collections.sort(counts);//www . j a v  a  2  s .c om
    Collections.reverse(counts);

    ArrayList<String> sortedAnnotations = new ArrayList<>();

    for (Integer count : counts) {
        for (String annotation : getAnnotations()) {
            if (annotationsMappedCount.get(annotation).equals(count)
                    && false == sortedAnnotations.contains(annotation)) {
                sortedAnnotations.add(annotation);
            }
        }
    }

    return sortedAnnotations;
}

From source file:es.udc.gii.common.eaf.algorithm.operator.selection.LinearRankingSelection.java

@Override
protected Individual select(EvolutionaryAlgorithm algorithm, List<Individual> individuals) {

    double random;
    double acum;/*from  ww w.j av  a  2s  . c o m*/
    int n = individuals.size();
    double min = 2 - this.max;
    double range = this.max - min;
    Individual individual;
    int i;

    //Se ordena la lista de individuos segn el comparador en orden inverso:
    Collections.sort(individuals, algorithm.getComparator());
    Collections.reverse(individuals);

    //Ahora la posicion en la lista de cada individuo indica su rank:
    random = EAFRandom.nextDouble();

    acum = 0.0;

    i = 0;
    do {

        i++;
        acum += (1.0 / n) * (this.max - range * ((double) (i - 1.0) / (double) (n - 1.0)));

    } while (acum < random);

    individual = individuals.get(--i);

    return (Individual) individual.clone();

}

From source file:com.netflix.curator.x.discovery.TestServiceCache.java

@Test
public void testInitialLoad() throws Exception {
    List<Closeable> closeables = Lists.newArrayList();
    TestingServer server = new TestingServer();
    closeables.add(server);//  w w w.  j  av  a  2  s  .  c o  m
    try {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class)
                .basePath("/discovery").client(client).build();
        closeables.add(discovery);
        discovery.start();

        ServiceCache<String> cache = discovery.serviceCacheBuilder().name("test").build();
        closeables.add(cache);

        final CountDownLatch latch = new CountDownLatch(3);
        ServiceCacheListener listener = new ServiceCacheListener() {
            @Override
            public void cacheChanged() {
                latch.countDown();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        cache.addListener(listener);
        cache.start();

        ServiceInstance<String> instance1 = ServiceInstance.<String>builder().payload("test").name("test")
                .port(10064).build();
        ServiceInstance<String> instance2 = ServiceInstance.<String>builder().payload("test").name("test")
                .port(10065).build();
        ServiceInstance<String> instance3 = ServiceInstance.<String>builder().payload("test").name("test")
                .port(10066).build();
        discovery.registerService(instance1);
        discovery.registerService(instance2);
        discovery.registerService(instance3);

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));

        ServiceCache<String> cache2 = discovery.serviceCacheBuilder().name("test").build();
        closeables.add(cache2);
        cache2.start();

        Assert.assertEquals(cache2.getInstances().size(), 3);
    } finally {
        Collections.reverse(closeables);
        for (Closeable c : closeables) {
            IOUtils.closeQuietly(c);
        }
    }
}

From source file:org.jfree.eastwood.GCategoryAxis.java

/**
 * Creates a temporary list of ticks that can be used when drawing the axis.
 *
 * @param g2  the graphics device (used to get font measurements).
 * @param state  the axis state./*from   w  w w  .ja v  a  2  s  .c om*/
 * @param dataArea  the area inside the axes.
 * @param edge  the location of the axis.
 *
 * @return A list of ticks.
 */
public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge) {

    List ticks = new java.util.ArrayList();

    // sanity check for data area...
    if (dataArea.getHeight() <= 0.0 || dataArea.getWidth() < 0.0) {
        return ticks;
    }

    CategoryPlot plot = (CategoryPlot) getPlot();
    List categories = null;
    if (this.labels == null) {
        categories = plot.getCategories();
    } else {
        categories = new java.util.ArrayList(this.labels);
        // handle a little quirk in the Google Chart API - for a horizontal
        // bar chart, the labels on the axis get applied in reverse order
        // relative to the data values
        if (plot.getOrientation() == PlotOrientation.HORIZONTAL) {
            Collections.reverse(categories);
        }
    }
    double max = 0.0;

    if (categories != null) {
        CategoryLabelPosition position = getCategoryLabelPositions().getLabelPosition(edge);
        float r = getMaximumCategoryLabelWidthRatio();
        if (r <= 0.0) {
            r = position.getWidthRatio();
        }

        float l = 0.0f;
        if (position.getWidthType() == CategoryLabelWidthType.CATEGORY) {
            l = (float) calculateCategorySize(categories.size(), dataArea, edge);
        } else {
            if (RectangleEdge.isLeftOrRight(edge)) {
                l = (float) dataArea.getWidth();
            } else {
                l = (float) dataArea.getHeight();
            }
        }
        int categoryIndex = 0;
        Iterator iterator = categories.iterator();
        while (iterator.hasNext()) {
            Comparable category = (Comparable) iterator.next();
            TextBlock label = createLabel(category, l * r, edge, g2);
            if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {
                max = Math.max(max, calculateTextBlockHeight(label, position, g2));
            } else if (edge == RectangleEdge.LEFT || edge == RectangleEdge.RIGHT) {
                max = Math.max(max, calculateTextBlockWidth(label, position, g2));
            }
            Tick tick = new CategoryTick(category, label, position.getLabelAnchor(),
                    position.getRotationAnchor(), position.getAngle());
            ticks.add(tick);
            categoryIndex = categoryIndex + 1;
        }
    }
    state.setMax(max);
    return ticks;

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.base.FenixContextAction.java

protected List<LabelValueBean> buildExecutionPeriodsLabelValueList(String degreeCurricularPlanId)
        throws FenixActionException {
    List<InfoExecutionDegree> infoExecutionDegreeList = new ArrayList<InfoExecutionDegree>();
    try {//from  www.j a  v a 2s .  c o  m

        infoExecutionDegreeList = ReadPublicExecutionDegreeByDCPID.run(degreeCurricularPlanId);
    } catch (Exception e) {
        throw new FenixActionException(e);
    }

    List<LabelValueBean> result = new ArrayList<LabelValueBean>();
    for (InfoExecutionDegree infoExecutionDegree : infoExecutionDegreeList) {

        try {
            List<InfoExecutionPeriod> infoExecutionPeriodsList = ReadNotClosedPublicExecutionPeriodsByExecutionYear
                    .run(infoExecutionDegree.getInfoExecutionYear());

            for (InfoExecutionPeriod infoExecutionPeriodIter : infoExecutionPeriodsList) {
                result.add(new LabelValueBean(
                        infoExecutionPeriodIter.getName() + " - "
                                + infoExecutionPeriodIter.getInfoExecutionYear().getYear(),
                        infoExecutionPeriodIter.getExternalId().toString()));
            }
        } catch (Exception e) {
            throw new FenixActionException(e);
        }
    }

    ComparatorChain comparatorChain = new ComparatorChain();
    comparatorChain.addComparator(new BeanComparator("value"));
    Collections.sort(result, comparatorChain);
    Collections.reverse(result);

    return result;
}

From source file:com.jgeppert.struts2.jquery.showcase.JsonTable.java

@Actions({ @Action(value = "/jsontable", results = { @Result(name = "success", type = "json") }) })
public String execute() {
    log.debug("Page " + getPage() + " Rows " + getRows() + " Sorting Order " + getSord() + " Index Row :"
            + getSidx());//from   w  w w.  j  a  v a  2  s . com
    log.debug("Search :" + searchField + " " + searchOper + " " + searchString);

    Object list = session.get("mylist");
    if (list != null) {
        myCustomers = (List<Customer>) list;
    } else {
        log.debug("Build new List");
        myCustomers = CustomerDAO.buildList();
    }

    if (sord != null && sord.equalsIgnoreCase("asc")) {
        Collections.sort(myCustomers);
    }
    if (sord != null && sord.equalsIgnoreCase("desc")) {
        Collections.sort(myCustomers);
        Collections.reverse(myCustomers);
    }

    // Count all record (select count(*) from your_custumers)
    records = CustomerDAO.getCustomersCount(myCustomers);

    if (totalrows != null) {
        records = totalrows;
    }

    // Calucalate until rows ware selected
    int to = (rows * page);

    // Calculate the first row to read
    int from = to - rows;

    // Set to = max rows
    if (to > records)
        to = records;

    if (loadonce) {
        if (totalrows != null && totalrows > 0) {
            setGridModel(myCustomers.subList(0, totalrows));
        } else {
            // All Custumer
            setGridModel(myCustomers);
        }
    } else {
        // Search Custumers
        if (searchString != null && searchOper != null) {
            int id = Integer.parseInt(searchString);
            if (searchOper.equalsIgnoreCase("eq")) {
                log.debug("search id equals " + id);
                List<Customer> cList = new ArrayList<Customer>();
                Customer customer = CustomerDAO.findById(myCustomers, id);

                if (customer != null)
                    cList.add(customer);

                setGridModel(cList);
            } else if (searchOper.equalsIgnoreCase("ne")) {
                log.debug("search id not " + id);
                setGridModel(CustomerDAO.findNotById(myCustomers, id, from, to));
            } else if (searchOper.equalsIgnoreCase("lt")) {
                log.debug("search id lesser then " + id);
                setGridModel(CustomerDAO.findLesserAsId(myCustomers, id, from, to));
            } else if (searchOper.equalsIgnoreCase("gt")) {
                log.debug("search id greater then " + id);
                setGridModel(CustomerDAO.findGreaterAsId(myCustomers, id, from, to));
            }
        } else {
            setGridModel(CustomerDAO.getCustomers(myCustomers, from, to));
        }
    }

    // Calculate total Pages
    total = (int) Math.ceil((double) records / (double) rows);

    // only for showcase functionality, don't do this in production
    session.put("mylist", myCustomers);

    return SUCCESS;
}