Example usage for java.util LinkedList removeLast

List of usage examples for java.util LinkedList removeLast

Introduction

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

Prototype

public E removeLast() 

Source Link

Document

Removes and returns the last element from this list.

Usage

From source file:MainClass.java

public static void main(String[] a) {

    LinkedList list = new LinkedList();
    list.add("A");
    list.add("B");
    list.add("C");
    list.add("D");
    list.addFirst("X");
    list.addLast("Z");

    System.out.println(list);/*  w w  w .  j av a  2  s.  c o  m*/
    System.out.println(list.getFirst());
    System.out.println(list.getLast());

    list.removeFirst();
    list.removeLast();

    System.out.println(list);
}

From source file:Main.java

public static void main(String[] args) {
    LinkedList<String> lList = new LinkedList<String>();

    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");

    System.out.println(lList);/*ww w .j a  v  a  2 s.c  o m*/
    Object object = lList.removeFirst();

    System.out.println(object + " has been removed");
    System.out.println(lList);

    object = lList.removeLast();
    System.out.println(object + " has been removed");
    System.out.println(lList);
}

From source file:MainClass.java

public static void main(String args[]) {

    LinkedList<String> ll = new LinkedList<String>();

    ll.add("B");//  w w  w .j a v  a  2  s  . c  om
    ll.add("C");
    ll.add("D");
    ll.add("E");
    ll.add("F");
    ll.addLast("Z");
    ll.addFirst("A");

    ll.add(1, "A2");

    System.out.println("Original contents of ll: " + ll);

    ll.remove("F");
    ll.remove(2);

    System.out.println("Contents of ll after deletion: " + ll);

    ll.removeFirst();
    ll.removeLast();

    System.out.println("ll after deleting first and last: " + ll);

    String val = ll.get(2);
    ll.set(2, val + " Changed");

    System.out.println("ll after change: " + ll);
}

From source file:org.eclipse.swordfish.core.configuration.xml.SaxParsingPrototype.java

/**
 * @param args/* w w  w.ja  va2s.c o m*/
 */
public static void main(String[] args) throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    LinkedList<String> currentElements = new LinkedList<String>();
    InputStream in = SaxParsingPrototype.class.getResource("ComplexPidXmlProperties.xml").openStream();
    XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
    Map<String, List<String>> props = new HashMap<String, List<String>>();
    // Read the XML document
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        if (event.isCharacters() && !event.asCharacters().isWhiteSpace()) {
            putElement(props, getQualifiedName(currentElements), event.asCharacters().getData());

        } else if (event.isStartElement()) {
            System.out.println(event.asStartElement().getName());
            currentElements.add(event.asStartElement().getName().getLocalPart());
            for (Iterator attrIt = event.asStartElement().getAttributes(); attrIt.hasNext();) {
                Attribute attribute = (Attribute) attrIt.next();
                putElement(props, getQualifiedName(currentElements) + "[@" + attribute.getName() + "]",
                        attribute.getValue());

            }
        } else if (event.isAttribute()) {
        } else if (event.isEndElement()) {
            String lastElem = event.asEndElement().getName().getLocalPart();
            if (!currentElements.getLast().equals(lastElem)) {
                throw new UnsupportedOperationException(lastElem + "," + currentElements.getLast());
            }
            currentElements.removeLast();
        }
    }

    eventReader.close();
}

From source file:org.diorite.config.impl.NestedNodesHelper.java

@SuppressWarnings("unchecked")
static void set(Object object, LinkedList<String> path, @Nullable Object newValue) {
    String last = path.removeLast();
    Object preLast;//from  w  w  w.  j  a  v  a  2 s.  co  m
    if (path.isEmpty()) {
        preLast = object;
    } else {
        preLast = get(object, path);
    }

    Validate.notNull(preLast);

    try {
        if (preLast instanceof Config) {
            ((Config) preLast).set(last, newValue);
        } else if (preLast instanceof Map) {
            ((Map<Object, Object>) preLast).put(last, newValue);
        } else if (preLast instanceof List) {
            List<Object> list = (List<Object>) preLast;
            int size = list.size();
            int index = Integer.parseInt(last);
            if (index == size) {
                list.add(newValue);
            } else if (index > size) {
                while (index > size++) {
                    list.add(null);
                }
                list.add(newValue);
            } else {
                list.set(index, newValue);
            }
        } else {
            Class<?> type = preLast.getClass();
            CacheKey cacheKey = new CacheKey(type, last);
            ReflectedProperty<?> property = propertyCache.computeIfAbsent(cacheKey,
                    k -> DioriteReflectionUtils.getReflectedProperty(last, type));
            property.set(preLast, newValue);
        }
    } catch (Exception e) {
        throw new IllegalStateException("Can't find property: " + last + " (" + path + ") in: " + preLast, e);
    }
}

From source file:Main.java

/**
 * Normalize a uri containing ../ and ./ paths.
 *
 * @param uri The uri path to normalize/*from  ww w .  j  a v a2  s  . c o m*/
 * @return The normalized uri
 */
public static String normalize(String uri) {
    if ("".equals(uri)) {
        return uri;
    }
    int leadingSlashes;
    for (leadingSlashes = 0; leadingSlashes < uri.length()
            && uri.charAt(leadingSlashes) == '/'; ++leadingSlashes) {
    }
    boolean isDir = (uri.charAt(uri.length() - 1) == '/');
    StringTokenizer st = new StringTokenizer(uri, "/");
    LinkedList clean = new LinkedList();
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        if ("..".equals(token)) {
            if (!clean.isEmpty() && !"..".equals(clean.getLast())) {
                clean.removeLast();
                if (!st.hasMoreTokens()) {
                    isDir = true;
                }
            } else {
                clean.add("..");
            }
        } else if (!".".equals(token) && !"".equals(token)) {
            clean.add(token);
        }
    }
    StringBuffer sb = new StringBuffer();
    while (leadingSlashes-- > 0) {
        sb.append('/');
    }
    for (Iterator it = clean.iterator(); it.hasNext();) {
        sb.append(it.next());
        if (it.hasNext()) {
            sb.append('/');
        }
    }
    if (isDir && sb.length() > 0 && sb.charAt(sb.length() - 1) != '/') {
        sb.append('/');
    }
    return sb.toString();
}

From source file:com.cyclopsgroup.waterview.utils.TagSupportBase.java

/**
 * Remove last script resource/*from   w  ww  . j a v  a  2 s.  co  m*/
 *
 * @param resource Resource to remove
 * @param context Jelly context
 */
public static final void removeScriptResource(URL resource, JellyContext context) {
    synchronized (context) {
        LinkedList scriptResources = (LinkedList) context.getVariable(SCRIPT_RESOURCE_NAME);
        if (scriptResources == null) {
            return;
        }
        URL last = (URL) scriptResources.getLast();
        if (last.sameFile(resource)) {
            scriptResources.removeLast();
        } else {
            throw new IllegalStateException("The resource to remove is not the last resource");
        }
    }
}

From source file:com.tamingtext.classifier.bayes.ExtractTrainingData.java

/**
 * Extract training data from a lucene index. 
 * <p>//from  w  ww .  ja v  a2 s .c  o m
 * Iterates over documents in the lucene index, the values in the categoryFields are inspected and if found to 
 * contain any of the strings found in the category file, a training data item will be emitted, assigned to the
 * matching category and containing the terms found in the fields listed in textFields. Output is written to
 * the output directory with one file per category.
 * <p>
 * The category file contains one line per category, each line contains a number of whitespace delimited strings. 
 * The first string on each line is the category name, while subsequent strings will be used to identify documents
 * that belong in that category.
 * <p>
 * 'Technology Computers Macintosh' will cause documents that contain either 'Technology', 'Computers' or 'Machintosh'
 * in one of their categoryFields to be assigned to the 'Technology' category.
 * 
 * 
 * @param indexDir 
 *   directory of lucene index to extract from
 *   
 * @param maxDocs
 *   the maximum number of documents to process.
 *   
 * @param categoryFile
 *   file containing category strings to extract
 *   
 * @param categoryFields
 *   list of fields to match against category data
 *   
 * @param textFields
 *   list of fields containing terms to extract
 *   
 * @param outputDir
 *   directory to write output to
 *   
 * @throws IOException
 */
public static void extractTraininingData(File indexDir, File categoryFile, Collection<String> categoryFields,
        Collection<String> textFields, File outputDir, boolean useTermVectors) throws IOException {

    log.info("Index dir: " + indexDir);
    log.info("Category file: " + categoryFile);
    log.info("Output dir: " + outputDir);
    log.info("Category fields: " + categoryFields.toString());
    log.info("Text fields: " + textFields.toString());
    log.info("Use Term Vectors?: " + useTermVectors);
    OpenObjectIntHashMap<String> categoryCounts = new OpenObjectIntHashMap<String>();
    Map<String, List<String>> categories = readCategoryFile(categoryFile);

    Directory dir = FSDirectory.open(indexDir);
    IndexReader reader = IndexReader.open(dir, true);
    int max = reader.maxDoc();

    StringBuilder buf = new StringBuilder();

    for (int i = 0; i < max; i++) {
        if (!reader.isDeleted(i)) {
            Document d = reader.document(i);
            String category = null;

            // determine whether any of the fields in this document contain a 
            // category in the category list
            fields: for (String field : categoryFields) {
                for (Field f : d.getFields(field)) {
                    if (f.isStored() && !f.isBinary()) {
                        String fieldValue = f.stringValue().toLowerCase();
                        for (String cat : categories.keySet()) {
                            List<String> cats = categories.get(cat);
                            for (String c : cats) {
                                if (fieldValue.contains(c)) {
                                    category = cat;
                                    break fields;
                                }
                            }
                        }
                    }
                }
            }

            if (category == null)
                continue;

            // append the terms from each of the textFields to the training data for this document.
            buf.setLength(0);
            for (String field : textFields) {
                if (useTermVectors) {
                    appendVectorTerms(buf, reader.getTermFreqVector(i, field));
                } else {
                    appendFieldText(buf, d.getField(field));
                }
            }
            getWriterForCategory(outputDir, category).printf("%s\t%s\n", category, buf.toString());
            categoryCounts.adjustOrPutValue(category, 1, 1);
        }
    }

    if (log.isInfoEnabled()) {
        StringBuilder b = new StringBuilder();
        b.append("\nCatagory document counts:\n");
        LinkedList<String> keyList = new LinkedList<String>();
        categoryCounts.keysSortedByValue(keyList);
        String key;
        while (!keyList.isEmpty()) {
            key = keyList.removeLast();
            b.append(categoryCounts.get(key)).append('\t').append(key).append('\n');
        }
        log.info(b.toString());
    }
}

From source file:de.undercouch.citeproc.helper.Levenshtein.java

/**
 * Searches the given collection of strings and returns a collection of at
 * most <code>n</code> strings that have the lowest Levenshtein distance
 * to a given string <code>t</code>. The returned collection will be
 * sorted according to the distance with the string with the lowest
 * distance at the first position.//from  w  ww. j a v  a 2s .  c o  m
 * @param <T> the type of the strings in the given collection
 * @param ss the collection to search
 * @param t the string to compare to
 * @param n the maximum number of strings to return
 * @param threshold a threshold for individual item distances. Only items
 * with a distance below this threshold will be included in the result.
 * @return the strings with the lowest Levenshtein distance
 */
public static <T extends CharSequence> Collection<T> findMinimum(Collection<T> ss, CharSequence t, int n,
        int threshold) {
    LinkedList<Item<T>> result = new LinkedList<Item<T>>();
    for (T s : ss) {
        int d = StringUtils.getLevenshteinDistance(s, t);
        if (d < threshold) {
            result.offer(new Item<T>(s, d));

            if (result.size() > n + 10) {
                //resort, but not too often
                Collections.sort(result);
                while (result.size() > n)
                    result.removeLast();
            }
        }
    }

    Collections.sort(result);
    while (result.size() > n)
        result.removeLast();

    List<T> arr = new ArrayList<T>(n);
    for (Item<T> i : result) {
        arr.add(i.str);
    }
    return arr;
}

From source file:org.apache.directory.studio.templateeditor.EntryTemplatePluginUtils.java

/**
 * Gets the list of matching templates for the given object class description.
 * <p>//from w w w  .jav  a  2 s . c om
 * To do this, we're using a "Breadth First Search" algorithm to go through all
 * the superiors (and the superiors of these superiors, etc.).
 *
 * @param objectClassDescription
 *      the object class description
 * @param schema
 *      the associated schema
 * @return
 *      the list of matching templates for the given object class description
 */
private static List<Template> getTemplatesFromHighestObjectClass(ObjectClass objectClassDescription,
        Schema schema) {
    // Creating a set to hold all the matching templates
    List<Template> matchingTemplates = new ArrayList<Template>();

    // Getting the templates manager
    TemplatesManager manager = EntryTemplatePlugin.getDefault().getTemplatesManager();

    // Getting the list of all the available templates
    Template[] templates = manager.getTemplates();

    // Creating a MultiValueMap that holds the templates ordered by ObjectClassDescription object
    MultiValueMap templatesByOcd = new MultiValueMap();

    // Populating this map
    for (Template template : templates) {
        templatesByOcd.put(getObjectClass(template.getStructuralObjectClass(), schema), template);
    }

    // Initializing the LIFO queue with the highest ObjectClassDescription object
    LinkedList<ObjectClass> ocdQueue = new LinkedList<ObjectClass>();
    ocdQueue.add(objectClassDescription);

    // Looking if we need to test a new ObjectClassDescription object
    while (!ocdQueue.isEmpty()) {
        // Dequeuing the last object for testing
        ObjectClass currentOcd = ocdQueue.removeLast();

        // Adds the templates for the current object class description to the list of matching templates
        addTemplatesForObjectClassDescription(currentOcd, matchingTemplates, manager);

        // Adding each superior object to the queue
        List<String> currentOcdSups = currentOcd.getSuperiorOids();
        if (currentOcdSups != null) {
            for (String currentOcdSup : currentOcdSups) {
                ocdQueue.addFirst(getObjectClass(currentOcdSup, schema));
            }
        }
    }

    return matchingTemplates;
}