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.admc.jcreole.marker.MarkerMap.java

/**
 * @param enumerationFormats is the starting numerationFormats used for
 *        header elements in the main body (the current body
 *        enumerationFormats can change as HeadingMarkers are encountered).
 *        This setting is independent of TOC levelInclusions, which is
 *        encapsulated nicely in TocMarker instances and not changed here
 *        (or elsewhere).//ww  w  .  j a  v  a2  s  .co  m
 */
public StringBuilder apply(StringBuilder sb, String enumerationFormats) {
    if (enumerationFormats == null)
        throw new NullPointerException("enumerationFormats may not be null");
    buffer = sb;
    for (BufferMarker m : values())
        if (m instanceof MasterDefListMarker) {
            masterDefListMarker = (MasterDefListMarker) m;
        } else if (m instanceof FootNotesMarker) {
            footNotesMarker = (FootNotesMarker) m;
        } else if (m instanceof IndexMarker) {
            indexMarker = (IndexMarker) m;
        }

    this.enumerationFormats = enumerationFormats;
    setContexts();
    List<BufferMarker> sortedMarkers = new ArrayList<BufferMarker>(values());
    Collections.sort(sortedMarkers);
    // Can not run insert() until after the markers have been sorted.
    if (size() < 1)
        return buffer;
    forwardPass1(sortedMarkers);
    int id;
    int offset3 = -1;
    int offset2 = -1;
    int offsetNl;
    EntryType eType;
    String idString;
    String name;
    while ((offset2 = buffer.indexOf("\u0002", offset3 + 1)) > -1) {
        // Load Entries (without data)
        offsetNl = buffer.indexOf("\n", offset2 + 2);
        if (offsetNl < 0)
            throw new CreoleParseException("No name termination for Entry");
        // Unfortunately StringBuilder has no indexOf(char).
        // We could do StringBuilder.toString().indexOf(char), but
        // that's a pretty expensive copy operation.
        offset3 = buffer.indexOf("\u0003", offsetNl + 1);
        if (offset3 < 0)
            throw new CreoleParseException("No termination for Entry");
        name = buffer.substring(offset2 + 2, offsetNl);
        if (name.length() < 1)
            throw new CreoleParseException("Empty embedded name for Entry");
        switch (buffer.charAt(offset2 + 1)) {
        case 'D':
            eType = EntryType.MASTERDEF;
            break;
        case 'F':
            eType = EntryType.FOOTNOTE;
            break;
        default:
            throw new CreoleParseException("Unexpected EntryType indicator: " + buffer.charAt(offset2 + 1));
        }
        if (footNotesMarker != null && eType == EntryType.FOOTNOTE) {
            footNotesMarker.add(name);
        } else if (masterDefListMarker != null && eType == EntryType.MASTERDEF) {
            masterDefListMarker.add(name);
        }
    }

    if (footNotesMarker != null) {
        footNotesMarker.sort();
        footNotesMarker.updateReferences();
    }
    if (masterDefListMarker != null) {
        masterDefListMarker.sort();
        masterDefListMarker.updateReferences();
    }
    if (indexMarker != null) {
        indexMarker.generateEntries();
        indexMarker.sort();
    }

    forwardPass2(sortedMarkers);
    log.debug(Integer.toString(sections.size()) + " Section headings: " + sections);
    // The list of markers MUST BE REVERSE SORTED before applying.
    // Applying in forward order would change buffer offsets.
    Collections.reverse(sortedMarkers);
    for (BufferMarker m : sortedMarkers)
        // N.b. this is where the real APPLY occurs to the buffer:
        if (!(m instanceof BodyUpdaterMarker))
            m.updateBuffer();

    // Can not move Entries until all of the normal \u001a markers have
    // been taken care of, because Styler directives depend on original
    // Creole sequence.

    // Extract all Entries
    offset2 = 0;
    while ((offset2 = buffer.indexOf("\u0002", offset2)) > -1) {
        // Load data for Entries
        offsetNl = buffer.indexOf("\n", offset2 + 2);
        if (offsetNl < 0)
            throw new CreoleParseException("No name termination for Entry");
        // Unfortunately StringBuilder has no indexOf(char).
        // We could do StringBuilder.toString().indexOf(char), but
        // that's a pretty expensive copy operation.
        offset3 = buffer.indexOf("\u0003", offsetNl + 1);
        if (offset3 < 0)
            throw new CreoleParseException("No termination for Entry");
        name = buffer.substring(offset2 + 2, offsetNl);
        if (name.length() < 1)
            throw new CreoleParseException("Empty embedded name for Entry");
        switch (buffer.charAt(offset2 + 1)) {
        case 'D':
            eType = EntryType.MASTERDEF;
            break;
        case 'F':
            eType = EntryType.FOOTNOTE;
            break;
        default:
            throw new CreoleParseException("Unexpected EntryType indicator: " + buffer.charAt(offset2 + 1));
        }
        if (footNotesMarker != null && eType == EntryType.FOOTNOTE)
            footNotesMarker.set(name, buffer.substring(offsetNl + 1, offset3));
        else if (masterDefListMarker != null && eType == EntryType.MASTERDEF)
            masterDefListMarker.set(name, buffer.substring(offsetNl + 1, offset3));
        buffer.delete(offset2, offset3 + 1);
    }

    // TODO: Consider whether to check for \u001a's inside of Entry p's,
    // which must be circular MasterDef or FootNotes markers.
    setContexts();
    Collections.sort(sortedMarkers);
    Collections.reverse(sortedMarkers);
    for (BufferMarker m : sortedMarkers)
        if (m == indexMarker)
            indexMarker.updateBuffer();
        else if (m == footNotesMarker)
            footNotesMarker.updateBuffer();
        else if (m == masterDefListMarker)
            masterDefListMarker.updateBuffer();
    return buffer;
}

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

@NotNull
@Override//w w  w  .  ja  v  a 2s  .co m
public var $negate() {
    LinkedHashMap<var, var> result = new LinkedHashMap<>();
    final ArrayList<Map.Entry<var, var>> entries = new ArrayList<>(map.entrySet());
    Collections.reverse(entries);
    for (Map.Entry<var, var> entry : entries) {
        result.put(entry.getKey(), entry.getValue());
    }
    return DollarFactory.fromValue(result, errors());
}

From source file:org.dspace.orm.entity.Collection.java

@Transient
public List<Community> getHierarchyList() {
    List<Community> parents = new ArrayList<Community>();
    Community tmp = this.getParent();
    while (tmp != null) {
        parents.add(tmp);/*  w w  w  .j a va 2 s. c o m*/
        if (tmp.hasParents()) {
            tmp = tmp.getParent();
        } else
            tmp = null;
    }
    Collections.reverse(parents);
    return parents;
}

From source file:com.adito.server.jetty.CustomWebApplicationContext.java

/**
 * <p>//from   w w  w. j  a v  a 2 s.  co m
 * Remove a Resrouce Cache. Whenever a resource is requested, this handler
 * will no longer use this cache.
 * 
 * <p>
 * This shouldn't be called directly, but through
 * {@link com.adito.boot.Context#removeResourceBase(URL)}
 * 
 * @param cache cache to remove
 */
public void removeResourceCache(ResourceCache cache) {
    resourceCaches.remove(cache);
    reverseCaches.clear();
    cacheState.clear();
    reverseCaches.addAll(resourceCaches);
    Collections.reverse(reverseCaches);
}

From source file:com.charts.YTDChart.java

protected OHLCDataItem[] getData(YStockQuote currentStock) throws ParseException {
    ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
    DateFormat df;//from  w w  w  . ja v  a2 s .co  m
    if (currentStock instanceof Index)
        df = new SimpleDateFormat("y-MM-dd");
    else
        df = new SimpleDateFormat("d-MM-yy");
    String OneYearDate = df.format(DayRange.ytd);
    ArrayList<String> historicalData = currentStock.get_historical_data();
    int length = historicalData.size();
    for (int i = 1; i < length; i++) {

        String[] data = historicalData.get(i).split(",");

        Date date = df.parse(data[0]);
        double open = Double.parseDouble(data[1]);
        double high = Double.parseDouble(data[2]);
        double low = Double.parseDouble(data[3]);
        double close = Double.parseDouble(data[4]);
        this.close.addOrUpdate(new Day(date), close);
        double volume;
        try {
            volume = Double.parseDouble(data[5]);
        } catch (NumberFormatException nfe) {
            volume = 0;
        }
        if (data[0].equals(OneYearDate)) {
            break;
        }

        OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
        dataItems.add(item);
    }
    Collections.reverse(dataItems);

    OHLCDataItem[] OHLCData = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
    return OHLCData;
}

From source file:com.charts.OneYearChart.java

protected OHLCDataItem[] getData(YStockQuote currentStock) throws ParseException {
    ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
    DateFormat df;/* w  ww . ja  v  a 2  s. co  m*/
    if (currentStock instanceof Index)
        df = new SimpleDateFormat("y-MM-dd");
    else
        df = new SimpleDateFormat("d-MM-yy");
    String OneYearDate = df.format(DayRange.one_year);
    ArrayList<String> historicalData = currentStock.get_historical_data();
    int length = historicalData.size();
    for (int i = 1; i < length; i++) {

        String[] data = historicalData.get(i).split(",");

        Date date = df.parse(data[0]);
        double open = Double.parseDouble(data[1]);
        double high = Double.parseDouble(data[2]);
        double low = Double.parseDouble(data[3]);
        double close = Double.parseDouble(data[4]);
        this.close.addOrUpdate(new Day(date), close);
        double volume;
        try {
            volume = Double.parseDouble(data[5]);
        } catch (NumberFormatException nfe) {
            volume = 0;
        }
        if (data[0].equals(OneYearDate)) {
            break;
        }

        OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
        dataItems.add(item);
    }
    Collections.reverse(dataItems);

    OHLCDataItem[] OHLCData = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
    return OHLCData;
}

From source file:nl.surfnet.coin.teams.domain.Invitation.java

public List<InvitationMessage> getInvitationMessagesReversed() {
    List<InvitationMessage> copy = new ArrayList<InvitationMessage>(invitationMessages.size());
    copy.addAll(invitationMessages);//from   w  w w .j a v  a  2  s. co m
    Collections.reverse(copy);
    return copy;
}

From source file:com.github.mrenou.jacksonatic.internal.introspection.AnnotatedClassConstructor.java

@SuppressWarnings("unchecked")
private Optional<ClassMappingInternal<Object>> getClassMappingFromSuperTypes(Class<?> type,
        ClassesMapping serOrDeserClassesMapping, ClassesMapping mergedClassesMapping) {
    List<Class<?>> superTypes = ClassUtil.findSuperTypes(type, Object.class);
    Collections.reverse(superTypes);
    return Stream.concat(Stream.of(Object.class), superTypes.stream())
            .map(superType -> (Class<Object>) superType)
            .map(superType -> Optional.ofNullable(mergedClassesMapping.getOpt(superType)
                    .orElseGet(() -> mergeAndPutInMergedClassesMapping(mergedClassesMapping, superType,
                            serOrDeserClassesMapping.getOpt(superType),
                            classesMappingByOperation.get(ANY).getOpt(superType)))))
            .reduce(Optional.empty(), Mergeable::merge);
}

From source file:org.n2.chess.beans.BoardService.java

@Override
public String createFen(Board board) {
    StringBuilder fen = new StringBuilder();
    boolean first = true;
    List<Row> rows = new ArrayList<Row>(board.getRowMap().values());
    Collections.reverse(rows);
    for (Row row : rows) {
        if (!first) {
            fen.append("/");
        }//  ww w. j  a v  a2 s  . c  om
        int empty = 0;
        List<Square> squares = new ArrayList<Square>(row.getSquareMap().values());
        Collections.reverse(squares);
        for (Square square : squares) {
            Piece piece = square.getPiece();
            if (piece != null) {
                if (empty > 0) {
                    fen.append(empty);
                    empty = 0;
                }
                fen.append(piece.getLetter());
            } else {
                empty++;
            }
        }
        if (empty > 0) {
            fen.append(empty);
        }
        first = false;
    }
    fen.append(" ").append(board.getActive());
    fen.append(" ").append(board.getCastling());
    fen.append(" ").append(board.getEnPassant());
    fen.append(" ").append(board.getHalfmove());
    fen.append(" ").append(board.getNumber());
    return fen.toString();
}

From source file:com.calc.BracerParser.java

/**
 * Parses the math expression (complicated formula) and stores the result
 *
 * @param expression <code>String</code> input expression (math formula)
 * @throws <code>ParseException</code> if the input expression is not
 *                                     correct
 * @since 3.0/*w w  w . j a  v a 2  s. c om*/
 */
public void parse(String expression) throws ParseException {
    /* cleaning stacks */
    stackOperations.clear();
    stackRPN.clear();

    /*
     * Faz algumas preparaes na String       
     */
    expression = expression.replace(" ", "").replace("(-", "(0-").replace(",-", ",0-").replace("(+", "(0+")
            .replace(",+", ",0+");
    if (expression.charAt(0) == '-' || expression.charAt(0) == '+') {
        expression = "0" + expression;
    }
    /* Separa a expresso em tokens */
    StringTokenizer stringTokenizer = new StringTokenizer(expression, OPERATORS + SEPARATOR + "()", true);

    /* shunting-yard algorithm */
    while (stringTokenizer.hasMoreTokens()) {
        String token = stringTokenizer.nextToken();
        if (isOpenBracket(token)) { //Se (
            stackOperations.push(token);
        } else if (isCloseBracket(token)) { //Se )
            while (!stackOperations.empty() && !isOpenBracket(stackOperations.lastElement())) {
                stackRPN.push(stackOperations.pop());
            }
            stackOperations.pop();
            if (!stackOperations.empty() && isFunction(stackOperations.lastElement())) {
                stackRPN.push(stackOperations.pop());
            }
        } else if (isNumber(token)) {
            if (token.equals(IMAGINARY)) {
                stackRPN.push(complexFormat.format(new Complex(0, 1)));
            } else if (token.contains(IMAGINARY)) {
                stackRPN.push(complexFormat.format(complexFormat.parse("0+" + token)));
            } else {
                stackRPN.push(token);
            }
        } else if (isOperator(token)) {
            while (!stackOperations.empty() && isOperator(stackOperations.lastElement())
                    && getPrecedence(token) <= getPrecedence(stackOperations.lastElement())) {
                stackRPN.push(stackOperations.pop());
            }
            stackOperations.push(token);
        } else if (isFunction(token)) {
            stackOperations.push(token);
        } else {
            throw new ParseException("Unrecognized token: " + token, 0);
        }
    }
    while (!stackOperations.empty()) {
        stackRPN.push(stackOperations.pop());
    }

    /* reverse stack */
    Collections.reverse(stackRPN);
}