Example usage for java.util LinkedList pollLast

List of usage examples for java.util LinkedList pollLast

Introduction

In this page you can find the example usage for java.util LinkedList pollLast.

Prototype

public E pollLast() 

Source Link

Document

Retrieves and removes the last element of this list, or returns null if this list is empty.

Usage

From source file:Main.java

public static void main(String[] args) {

    // create a LinkedList
    LinkedList<String> list = new LinkedList<String>();

    // add some elements
    list.add("Hello");
    list.add("from java2s.com");
    list.add("10");

    // print the list
    System.out.println("LinkedList:" + list);

    // retrieve and remove the last element of the list
    System.out.println("Last element of the list:" + list.pollLast());

    // print the list
    System.out.println("LinkedList:" + list);
}

From source file:com.mohawk.webcrawler.ScriptCompiler.java

/**
 *
 * @param tokens/*from  w  ww . j av a 2  s  .com*/
 * @param parentScope
 */
private static void addScope(Queue<String> tokens, Queue<? super BaseToken> parentScope)
        throws CompilationException {

    while (!tokens.isEmpty()) {

        String token = tokens.poll();
        if ("end".equals(token) || "else".equals(token) || "elseif".equals(token)) {
            parentScope.add(new BaseEndScope(token));
            break;
        } else if ("if".equals(token)) {
            String expression = tokens.poll();

            If_Verb ifVerb = new If_Verb();
            ifVerb.setExpression(expression);

            parentScope.add(ifVerb);
            addScope(tokens, ifVerb.createScope());

            // check if elseif or else is defined
            LinkedList<BaseToken> ifScope = ifVerb.getScope();
            Object elseToken = ifScope.peekLast();

            if (elseToken instanceof BaseEndScope) {
                // remove elseif or else from if scope
                ifScope.pollLast();

                while (elseToken instanceof BaseEndScope) {

                    String elseStr = ((BaseEndScope) elseToken).getName();
                    if ("end".equals(elseStr))
                        break;
                    else if ("elseif".equals(elseStr)) {

                        String exp = tokens.poll();
                        ElseIf_Verb elseIfVerb = new ElseIf_Verb();
                        elseIfVerb.setExpression(exp);
                        ifVerb.addElseIf(elseIfVerb);

                        addScope(tokens, elseIfVerb.createScope());
                        elseToken = elseIfVerb.getScope().pollLast();
                    } else if ("else".equals(elseStr)) {

                        Else_Verb elseVerb = new Else_Verb();
                        ifVerb.setElse(elseVerb);

                        addScope(tokens, elseVerb.createScope());
                        elseToken = elseVerb.getScope().pollLast();
                    }
                }
            }
        } else if ("while".equals(token)) {

            String evaluation = tokens.poll();

            While_Verb whileVerb = new While_Verb();
            whileVerb.setExpression(evaluation);

            parentScope.add(whileVerb);
            addScope(tokens, whileVerb.createScope());
        } else if (LangCore.isVerb(token)) { // verb
            try {
                parentScope.add(LangCore.createVerbToken((String) token));
            } catch (Exception e) {
                e.printStackTrace();
                throw new CompilationException(e.getLocalizedMessage());
            }
        } else if (LangCore.isLiteral(token)) { // literal
            try {
                parentScope.add(new BaseLiteral(LangCore.createLiteralObject(token)));
            } catch (LanguageException e) {
                throw new CompilationException(e.getLocalizedMessage());
            }
        } else if (LangCore.isOperator(token)) { // operator
            try {
                parentScope.add(LangCore.createOperatorToken(token));
            } catch (LanguageException e) {
                throw new CompilationException(e.getLocalizedMessage());
            }
        } else // default to variable
            parentScope.add(new BaseVariable(token));
    }
}

From source file:eulermind.importer.LineNode.java

private static LinkedList<LineNode> popSameBlankLineNodes(LinkedList<LineNode> stack) {
    int lastBlankLines = stack.peekLast().m_blankLines;
    LinkedList<LineNode> lastSameLineNodes = new LinkedList<LineNode>();

    while (!stack.isEmpty() && stack.peekLast().m_blankLines == lastBlankLines) {
        //pollLast? addFirst??
        lastSameLineNodes.addFirst(stack.pollLast());
    }/*from ww w  .  j a  v  a  2 s .c  om*/
    return lastSameLineNodes;
}

From source file:ca.uhn.fhir.context.RuntimeResourceDefinition.java

private void fillProfile(Structure theStruct, StructureElement theElement, BaseRuntimeElementDefinition<?> def,
        LinkedList<String> path, BaseRuntimeDeclaredChildDefinition theChild) {

    fillBasics(theElement, def, path, theChild);

    String expectedPath = StringUtils.join(path, '.');

    ourLog.info("Filling profile for: {} - Path: {}", expectedPath);
    String name = def.getName();/*from  w w  w .j a  va 2  s  .c  o m*/
    if (!expectedPath.equals(name)) {
        path.pollLast();
        theElement.getDefinition().getNameReference().setValue(def.getName());
        return;
    }

    fillExtensions(theStruct, path, def.getExtensionsNonModifier(), "extension", false);
    fillExtensions(theStruct, path, def.getExtensionsModifier(), "modifierExtension", true);

    if (def.getChildType() == ChildTypeEnum.RESOURCE) {
        StructureElement narrative = theStruct.addElement();
        narrative.setName("text");
        narrative.setPath(join(path, '.') + ".text");
        narrative.getDefinition().addType().setCode(DataTypeEnum.NARRATIVE);
        narrative.getDefinition().setIsModifier(false);
        narrative.getDefinition().setMin(0);
        narrative.getDefinition().setMax("1");

        StructureElement contained = theStruct.addElement();
        contained.setName("contained");
        contained.setPath(join(path, '.') + ".contained");
        contained.getDefinition().addType().getCode().setValue("Resource");
        contained.getDefinition().setIsModifier(false);
        contained.getDefinition().setMin(0);
        contained.getDefinition().setMax("1");
    }

    if (def instanceof BaseRuntimeElementCompositeDefinition) {
        BaseRuntimeElementCompositeDefinition<?> cdef = ((BaseRuntimeElementCompositeDefinition<?>) def);
        for (BaseRuntimeChildDefinition nextChild : cdef.getChildren()) {
            if (nextChild instanceof RuntimeChildUndeclaredExtensionDefinition) {
                continue;
            }

            BaseRuntimeDeclaredChildDefinition child = (BaseRuntimeDeclaredChildDefinition) nextChild;
            StructureElement elem = theStruct.addElement();
            fillMinAndMaxAndDefinitions(child, elem);

            if (child instanceof RuntimeChildResourceBlockDefinition) {
                RuntimeResourceBlockDefinition nextDef = (RuntimeResourceBlockDefinition) child
                        .getSingleChildOrThrow();
                fillProfile(theStruct, elem, nextDef, path, child);
            } else if (child instanceof RuntimeChildContainedResources) {
                // ignore
            } else if (child instanceof RuntimeChildDeclaredExtensionDefinition) {
                throw new IllegalStateException(
                        "Unexpected child type: " + child.getClass().getCanonicalName());
            } else if (child instanceof RuntimeChildCompositeDatatypeDefinition
                    || child instanceof RuntimeChildPrimitiveDatatypeDefinition
                    || child instanceof RuntimeChildChoiceDefinition
                    || child instanceof RuntimeChildResourceDefinition) {
                Iterator<String> childNamesIter = child.getValidChildNames().iterator();
                String nextName = childNamesIter.next();
                BaseRuntimeElementDefinition<?> nextDef = child.getChildByName(nextName);
                fillBasics(elem, nextDef, path, child);
                fillName(elem, nextDef);
                while (childNamesIter.hasNext()) {
                    nextDef = child.getChildByName(childNamesIter.next());
                    fillName(elem, nextDef);
                }
                path.pollLast();
            } else {
                throw new IllegalStateException(
                        "Unexpected child type: " + child.getClass().getCanonicalName());
            }

        }
    } else {
        throw new IllegalStateException("Unexpected child type: " + def.getClass().getCanonicalName());
    }

    path.pollLast();
}

From source file:ca.uhn.fhir.model.dstu.FhirDstu1.java

private void fillProfile(Structure theStruct, StructureElement theElement, BaseRuntimeElementDefinition<?> def,
        LinkedList<String> path, BaseRuntimeDeclaredChildDefinition theChild, String theServerBase) {

    fillBasics(theElement, def, path, theChild);

    String expectedPath = StringUtils.join(path, '.');

    ourLog.debug("Filling profile for: {} - Path: {}", expectedPath);
    String name = def.getName();/*from w  w w  .j  a  va2  s . c o m*/
    if (!expectedPath.equals(name)) {
        path.pollLast();
        theElement.getDefinition().getNameReference().setValue(def.getName());
        return;
    }

    fillExtensions(theStruct, path, def.getExtensionsNonModifier(), "extension", false);
    fillExtensions(theStruct, path, def.getExtensionsModifier(), "modifierExtension", true);

    if (def.getChildType() == ChildTypeEnum.RESOURCE) {
        StructureElement narrative = theStruct.addElement();
        narrative.setName("text");
        narrative.setPath(join(path, '.') + ".text");
        narrative.getDefinition().addType().setCode(DataTypeEnum.NARRATIVE);
        narrative.getDefinition().setIsModifier(false);
        narrative.getDefinition().setMin(0);
        narrative.getDefinition().setMax("1");

        StructureElement contained = theStruct.addElement();
        contained.setName("contained");
        contained.setPath(join(path, '.') + ".contained");
        contained.getDefinition().addType().getCode().setValue("Resource");
        contained.getDefinition().setIsModifier(false);
        contained.getDefinition().setMin(0);
        contained.getDefinition().setMax("1");
    }

    if (def instanceof BaseRuntimeElementCompositeDefinition) {
        BaseRuntimeElementCompositeDefinition<?> cdef = ((BaseRuntimeElementCompositeDefinition<?>) def);
        for (BaseRuntimeChildDefinition nextChild : cdef.getChildren()) {
            if (nextChild instanceof RuntimeChildUndeclaredExtensionDefinition) {
                continue;
            }
            if (nextChild instanceof RuntimeChildExtension) {
                continue;
            }

            BaseRuntimeDeclaredChildDefinition child = (BaseRuntimeDeclaredChildDefinition) nextChild;
            StructureElement elem = theStruct.addElement();
            fillMinAndMaxAndDefinitions(child, elem);

            if (child instanceof RuntimeChildResourceBlockDefinition) {
                RuntimeResourceBlockDefinition nextDef = (RuntimeResourceBlockDefinition) child
                        .getSingleChildOrThrow();
                fillProfile(theStruct, elem, nextDef, path, child, theServerBase);
            } else if (child instanceof RuntimeChildContainedResources) {
                // ignore
            } else if (child instanceof RuntimeChildDeclaredExtensionDefinition) {
                throw new IllegalStateException(
                        "Unexpected child type: " + child.getClass().getCanonicalName());
            } else if (child instanceof RuntimeChildCompositeDatatypeDefinition
                    || child instanceof RuntimeChildPrimitiveDatatypeDefinition
                    || child instanceof RuntimeChildChoiceDefinition
                    || child instanceof RuntimeChildResourceDefinition) {
                Iterator<String> childNamesIter = child.getValidChildNames().iterator();
                String nextName = childNamesIter.next();
                BaseRuntimeElementDefinition<?> nextDef = child.getChildByName(nextName);
                fillBasics(elem, nextDef, path, child);
                fillName(elem, nextDef, theServerBase);
                while (childNamesIter.hasNext()) {
                    nextDef = child.getChildByName(childNamesIter.next());
                    fillName(elem, nextDef, theServerBase);
                }
                path.pollLast();
            } else {
                throw new IllegalStateException(
                        "Unexpected child type: " + child.getClass().getCanonicalName());
            }

        }
    } else {
        throw new IllegalStateException("Unexpected child type: " + def.getClass().getCanonicalName());
    }

    path.pollLast();
}

From source file:com.moorestudio.seniorimageprocessing.SeniorSorter.java

public void sortImages() {
    LinkedList<Map.Entry<String, Long>> timestampList = new LinkedList<>(timestampData.entrySet());
    sort(timestampList, (x, y) -> x.getValue() > y.getValue() ? -1 : x.getValue().equals(y.getValue()) ? 0 : 1);
    // Sort in reverse so that the most recent timestamps are first.e so that the most recent timestamps are first.

    LinkedList<Map.Entry<File, Long>> imageDataList = new LinkedList<>(imageData.entrySet());
    sort(imageDataList, (x, y) -> x.getValue() > y.getValue() ? -1 : x.getValue().equals(y.getValue()) ? 0 : 1); // Sort in reverse so that the most recent timestamps are first.

    // For the gui update
    int idCount = imageDataList.size();

    //Take the first image and the first timestamp scan taken, which is last in the list, 
    //and sync the camera time to the timestamp time.Both are throwaways.
    if (!timestampList.isEmpty() && !imageDataList.isEmpty() && parent.syncTime) {
        Map.Entry<File, Long> iData = imageDataList.pollLast();
        Map.Entry<String, Long> tsData = timestampList.pollLast();

        //Make the offset
        cameraTimeOffset = tsData.getValue() - iData.getValue();
    }//from  ww  w.  j  a  v a2s  .  co  m

    //add the file to the top timestamp student until it is no longer more than it
    while (!timestampList.isEmpty() && !imageDataList.isEmpty()) {
        Map.Entry<File, Long> iData = imageDataList.peekFirst();
        Map.Entry<String, Long> tsData = timestampList.pollFirst();
        ArrayList<File> studentImages = new ArrayList<>();
        while (!imageDataList.isEmpty() && iData.getValue() + cameraTimeOffset > tsData.getValue()) {
            iData = imageDataList.pollFirst();
            studentImages.add(iData.getKey());
            iData = imageDataList.peekFirst();
            //update the GUI
            parent.addProgress((.125 / parent.numThreads) / idCount);
        }
        if (!studentImages.isEmpty()) {
            parent.addImagesToStudent(tsData.getKey(), studentImages);
        }
    }

    //add the unsorted images to the parent's unsorted queue
    for (Map.Entry<File, Long> entry : imageDataList) {
        parent.unsortedFiles.add(entry.getKey());
        //update the GUI
        parent.addProgress((.125 / parent.numThreads) / idCount);
    }
}

From source file:com.google.ie.business.service.impl.IdeaServiceImpl.java

@SuppressWarnings("unchecked")
public void addIdeaToListInCache(Idea originalIdea, String keyOfTheList, int noOfIdeas, int expiryDelay) {
    LinkedList<Idea> listOfIdeas = (LinkedList<Idea>) CacheHelper.getObject(CacheConstants.IDEA_NAMESPACE,
            keyOfTheList);//ww w. j ava  2s  .c o m
    if (listOfIdeas != null) {
        if (listOfIdeas.size() >= noOfIdeas) {
            /* Remove the last element which is also the oldest */
            listOfIdeas.pollLast();
        }
    } else {
        listOfIdeas = new LinkedList<Idea>();
    }
    /* Create a new idea object to contain the required data only */
    Idea ideaWithTheRequiredDataOnly = new Idea();
    ideaWithTheRequiredDataOnly
            .setTitle(StringUtils.abbreviate(originalIdea.getTitle(), ServiceConstants.FIFTY));
    /* Limit the description to hundred characters */
    ideaWithTheRequiredDataOnly
            .setDescription(StringUtils.abbreviate(originalIdea.getDescription(), ServiceConstants.HUNDRED));
    ideaWithTheRequiredDataOnly.setKey(originalIdea.getKey());
    /* Add the idea to the head of the list */
    listOfIdeas.addFirst(ideaWithTheRequiredDataOnly);
    /* Put the updated list back to the cache */
    CacheHelper.putObject(CacheConstants.IDEA_NAMESPACE, keyOfTheList, listOfIdeas, expiryDelay);
}

From source file:nf.frex.android.FrexActivity.java

@Override
public void onBackPressed() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean navigateOnBack = preferences.getBoolean("navigate_on_back", false);
    if (!navigateOnBack) {
        super.onBackPressed();
        return;//from   w w  w. j av  a  2s  . c o  m
    }

    LinkedList<Region> regionHistory = view.getRegionHistory();
    if (regionHistory.size() > 0) {
        Region region;
        if (regionHistory.size() == 1) {
            region = regionHistory.get(0);
            alert(getString(R.string.first_region_msg));
        } else {
            region = regionHistory.pollLast();
        }
        view.setRegionRecordingDisabled(true);
        view.regenerateRegion(region);
        view.setRegionRecordingDisabled(false);
    } else {
        alert(getString(R.string.empty_region_history_msg));
    }
}

From source file:es.emergya.ui.plugins.admin.aux1.SummaryAction.java

private void reorder(int inicio, int fin) {

    boolean sentido = inicio < fin;

    LinkedList<Object> aSubir = new LinkedList<Object>();
    LinkedList<Object> resultado = new LinkedList<Object>();

    for (Object o : right.getSelectedValues()) {
        aSubir.add(o);/*from w w  w.j  ava  2s. c  o m*/
    }

    final DefaultListModel defaultListModel = (DefaultListModel) right.getModel();

    if (log.isTraceEnabled()) {
        log.trace("Elementos seleccionados:");
        for (Object o : aSubir) {
            log.trace(o + " " + o.getClass());
        }
    }

    for (int i = inicio; (sentido ? i <= fin : fin <= i); i = (sentido ? i + 1 : i - 1)) {
        Object o = defaultListModel.get(i);
        if (aSubir.contains(o) && i != inicio) {
            Object siguiente = resultado.pollLast();
            log.trace("Cambiamos " + o + " por " + siguiente);
            resultado.add(o);
            resultado.add(siguiente);
        } else {
            log.trace("Aadimos " + o);
            resultado.add(o);
        }
    }

    ((DefaultListModel) right.getModel()).removeAllElements();
    log.trace("Nueva lista: ");

    int inicio2 = (sentido ? 0 : resultado.size() - 1);
    int fin2 = (sentido ? resultado.size() - 1 : 0);
    for (int i = inicio2; (sentido ? i <= fin2 : fin2 <= i); i = (sentido ? i + 1 : i - 1)) {
        Object o = resultado.get(i);
        log.trace("Nueva lista >" + o);
        ((DefaultListModel) right.getModel()).addElement(o);
    }

    int seleccion[] = new int[aSubir.size()];
    int k = 0;
    for (Integer i = 0; i < right.getModel().getSize(); i++) {
        if (aSubir.contains(right.getModel().getElementAt(i))) {
            seleccion[k++] = i;
        }
    }

    right.setSelectedIndices(seleccion);

    right.updateUI();
}

From source file:de.betterform.agent.web.event.EventQueue.java

public List<XMLEvent> aggregateEventList() {
    // Stack is used to "navigate" through the event list
    LinkedList<XMLEvent> aggregatedFocusList = new LinkedList<XMLEvent>();
    Stack<XMLEvent> aggregatedInsertEventsStack = new Stack();
    Stack<XMLEvent> aggregatedEmbedEventsStack = new Stack();
    ArrayList<XMLEvent> aggregatedEventList = new ArrayList<XMLEvent>(eventList.size());

    for (XMLEvent xmlEvent : this.loadEmbedEventList) {
        aggregatedEventList.add(xmlEvent);
    }//from   w ww.  j  a v  a 2s .  c  o m

    this.loadEmbedEventList.clear();

    for (int i = 0; i < eventList.size(); i++) {
        XercesXMLEvent xmlEvent = (XercesXMLEvent) eventList.get(i);

        XercesXMLEvent xmlEventToAdd = new XercesXMLEvent();
        // Map PROTOTYPE_CLONED event to betterform-insert-repeatitem or betterform-insert-itemset event
        // and copy event properties to new created XMLEvent
        if (xmlEvent.getType().equals(BetterFormEventNames.PROTOTYPE_CLONED)) {
            if (xmlEvent.getContextInfo("targetName").equals(XFormsConstants.ITEMSET)) {
                xmlEventToAdd.initXMLEvent("betterform-insert-itemset", xmlEvent.getBubbles(),
                        xmlEvent.getCancelable(), xmlEvent.getContextInfo());
            } else {
                xmlEventToAdd.initXMLEvent("betterform-insert-repeatitem", xmlEvent.getBubbles(),
                        xmlEvent.getCancelable(), xmlEvent.getContextInfo());
            }
            xmlEventToAdd.target = xmlEvent.target;
            xmlEvent.addProperty("generatedIds", new HashMap());
            aggregatedEventList.add(xmlEventToAdd);
            // push XMLEvent to Stack for further processing
            aggregatedInsertEventsStack.push(xmlEventToAdd);

        }
        // add all generated ids to surrounding betterform-insert-repeatitem or betterform-insert-itemset event
        else if (xmlEvent.getType().equals(BetterFormEventNames.ID_GENERATED)
                && aggregatedInsertEventsStack.size() > 0) {
            XMLEvent aggregatingInsertEvent = aggregatedInsertEventsStack.peek();
            ((HashMap) aggregatingInsertEvent.getContextInfo("generatedIds"))
                    .put(xmlEvent.getContextInfo("originalId"), xmlEvent.getContextInfo("targetId"));
        }
        // add insert position to surrounding betterform-insert-repeatitem or betterform-insert-itemset event
        else if (xmlEvent.getType().equals(BetterFormEventNames.ITEM_INSERTED)) {
            XMLEvent tmpEvent = aggregatedInsertEventsStack.pop();
            tmpEvent.addProperty("position", xmlEvent.getContextInfo("position"));
            tmpEvent.addProperty("label", xmlEvent.getContextInfo("label"));
            tmpEvent.addProperty("value", xmlEvent.getContextInfo("value"));

        } else if (xmlEvent.getType().equals(BetterFormEventNames.EMBED)) {
            aggregatedEventList.add(xmlEvent);
            aggregatedEmbedEventsStack.push(xmlEvent);
        } else if (xmlEvent.getType().equals(BetterFormEventNames.EMBED_DONE)) {
            aggregatedEmbedEventsStack.pop().addProperty("targetElement",
                    xmlEvent.getContextInfo("targetElement"));
            aggregatedEventList.add(xmlEvent);
        } else if (xmlEvent.getType().equals(XFormsEventNames.FOCUS)) {
            aggregatedFocusList.push(xmlEvent);
        }
        /* else if(xmlEvent.getType().equals(BetterFormEventNames.INDEX_CHANGED)){
        aggregatedFocusList.push(xmlEvent);
        }*/
        // all other events within eventList are simply copied to the new eventlist
        else {
            aggregatedEventList.add(xmlEvent);
        }
    }

    while (!aggregatedFocusList.isEmpty()) {
        aggregatedEventList.add(aggregatedFocusList.pollLast());
    }
    return aggregatedEventList;
}