Example usage for java.util Deque removeFirst

List of usage examples for java.util Deque removeFirst

Introduction

In this page you can find the example usage for java.util Deque removeFirst.

Prototype

E removeFirst();

Source Link

Document

Retrieves and removes the first element of this deque.

Usage

From source file:Main.java

public static void main(String[] args) {

    Deque<Integer> deque = new ArrayDeque<Integer>(8);

    deque.add(15);//from   w  w w. ja v a2  s. com
    deque.add(30);
    deque.add(25);
    deque.add(40);

    // this will remove element at the first(head) postion
    int retval = deque.removeFirst();
    System.out.println("Element removed is: " + retval);

    System.out.println(deque);
}

From source file:Main.java

public static void main(String[] args) {
    Deque<String> deque = new LinkedList<>();
    deque.addLast("Oracle");
    deque.offerLast("Java");
    deque.offerLast("CSS");
    deque.offerLast("XML");

    System.out.println("Deque: " + deque);

    // remove elements from the Deque until it is empty
    while (deque.peekFirst() != null) {
        System.out.println("Head  Element: " + deque.peekFirst());
        deque.removeFirst();
        System.out.println("Removed one  element from  Deque");
        System.out.println("Deque: " + deque);
    }/*from   ww  w  .  ja v a  2  s.com*/

    // the Deque is empty. Try to call its peekFirst(),
    // getFirst(), pollFirst() and removeFirst() methods
    System.out.println("deque.isEmpty(): " + deque.isEmpty());

    System.out.println("deque.peekFirst(): " + deque.peekFirst());
    System.out.println("deque.pollFirst(): " + deque.pollFirst());

    String str = deque.getFirst();
    System.out.println("deque.getFirst(): " + str);
    str = deque.removeFirst();
    System.out.println("deque.removeFirst(): " + str);

}

From source file:cz.cuni.mff.ksi.jinfer.autoeditor.automatonvisualizer.layouts.graphviz.AutomatonToDot.java

public static <T> String convertToDot(final Automaton<T> automaton,
        final Transformer<Step<T>, String> edgeLabelTransformer) {
    final StringBuilder sb = new StringBuilder();
    sb.append("digraph finite_state_machine {\n");
    sb.append("\trankdir=LR;\n");
    sb.append("\tnodesep=\"50\";");
    sb.append("\tsplines=\"line\";");
    sb.append("\tranksep=\"100\";");
    sb.append("\tedge [label = \"\", dir = none, arrowhead=none, arrowtail=none];");
    sb.append("\tnode [shape = none, label = \"\", width = 0, height = 0];\n");
    final Deque<State<T>> queue = new ArrayDeque<State<T>>();
    queue.addAll(automaton.getDelta().keySet());

    while (!queue.isEmpty()) {
        final State<T> actual = queue.removeFirst();
        sb.append(actual.getName());//  ww w.  ja v  a2  s .com
        sb.append(";\n");
        for (Step<T> step : automaton.getDelta().get(actual)) {
            sb.append("\t");
            sb.append(step.getSource().getName());
            sb.append(" -> ");
            sb.append(step.getDestination().getName());
            sb.append("];\n");
        }
    }
    sb.append("\n}");
    return sb.toString();
}

From source file:info.servertools.core.util.FileUtils.java

public static void zipDirectory(File directory, File zipfile, @Nullable Collection<String> fileBlacklist,
        @Nullable Collection<String> folderBlacklist) throws IOException {
    URI baseDir = directory.toURI();
    Deque<File> queue = new LinkedList<>();
    queue.push(directory);/*  w ww. j  ava 2  s.c o  m*/
    OutputStream out = new FileOutputStream(zipfile);
    Closeable res = out;
    try {
        ZipOutputStream zout = new ZipOutputStream(out);
        res = zout;
        while (!queue.isEmpty()) {
            directory = queue.removeFirst();
            File[] dirFiles = directory.listFiles();
            if (dirFiles != null && dirFiles.length != 0) {
                for (File child : dirFiles) {
                    if (child != null) {
                        String name = baseDir.relativize(child.toURI()).getPath();
                        if (child.isDirectory()
                                && (folderBlacklist == null || !folderBlacklist.contains(child.getName()))) {
                            queue.push(child);
                            name = name.endsWith("/") ? name : name + "/";
                            zout.putNextEntry(new ZipEntry(name));
                        } else {
                            if (fileBlacklist != null && !fileBlacklist.contains(child.getName())) {
                                zout.putNextEntry(new ZipEntry(name));
                                copy(child, zout);
                                zout.closeEntry();
                            }
                        }
                    }
                }
            }
        }
    } finally {
        res.close();
    }
}

From source file:com.espertech.esper.event.EventTypeUtility.java

public static EventPropertyDescriptor getNestablePropertyDescriptor(EventType target, Deque<Property> stack) {

    Property topProperty = stack.removeFirst();
    if (stack.isEmpty()) {
        return target.getPropertyDescriptor(((PropertyBase) topProperty).getPropertyNameAtomic());
    }//from w w w .  j a  va  2  s  .  com

    if (!(topProperty instanceof SimpleProperty)) {
        return null;
    }
    SimpleProperty simple = (SimpleProperty) topProperty;

    FragmentEventType fragmentEventType = target.getFragmentType(simple.getPropertyNameAtomic());
    if (fragmentEventType == null || fragmentEventType.getFragmentType() == null) {
        return null;
    }
    return getNestablePropertyDescriptor(fragmentEventType.getFragmentType(), stack);
}

From source file:cz.cuni.mff.ksi.jinfer.autoeditor.automatonvisualizer.layouts.AutomatonToDot.java

public String convertToDot(Automaton<T> automaton, Transformer<Step<T>, String> edgeLabelTransformer) {
    StringBuilder sb = new StringBuilder();
    sb.append("digraph finite_state_machine {\n" + "\trankdir=LR;\n" + "\tnode [shape = circle];\n");
    List<State<T>> finiteStates = new LinkedList<State<T>>();
    Deque<State<T>> queue = new ArrayDeque<State<T>>();
    Set<State<T>> visited = new HashSet<State<T>>();
    queue.addLast(automaton.getInitialState());
    visited.add(automaton.getInitialState());
    while (!queue.isEmpty()) {
        State<T> actual = queue.removeFirst();
        if (actual.getFinalCount() > 0) {
            finiteStates.add(actual);/*from w ww  .j  a v a 2s. com*/
        }
        for (Step<T> step : automaton.getDelta().get(actual)) {
            sb.append("\t");
            sb.append(step.getSource().getName());
            sb.append(" -> ");
            sb.append(step.getDestination().getName());
            sb.append(" [ label = \"");
            sb.append(edgeLabelTransformer.transform(step));
            sb.append("|");
            sb.append(step.getUseCount());
            sb.append("\" ];\n");
            if (!visited.contains(step.getDestination())) {
                queue.addLast(step.getDestination());
                visited.add(step.getDestination());
            }
        }
    }
    sb.append("\n}");
    return sb.toString();
}

From source file:io.anserini.index.IndexWebCollection.java

public int indexWithThreads(int numThreads) throws IOException, InterruptedException {

    LOG.info("Indexing with " + numThreads + " threads to directory '" + indexPath.toAbsolutePath() + "'...");

    final Directory dir = FSDirectory.open(indexPath);

    final IndexWriterConfig iwc = new IndexWriterConfig(new EnglishAnalyzer());

    iwc.setSimilarity(new BM25Similarity());
    iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    iwc.setRAMBufferSizeMB(512);//ww w  .  j ava 2 s .  c  o  m
    iwc.setUseCompoundFile(false);
    iwc.setMergeScheduler(new ConcurrentMergeScheduler());

    final IndexWriter writer = new IndexWriter(dir, iwc);

    final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(numThreads);
    final String suffix = Collection.GOV2.equals(collection) ? ".gz" : ".warc.gz";
    final Deque<Path> warcFiles = discoverWarcFiles(docDir, suffix);

    if (doclimit > 0 && warcFiles.size() < doclimit)
        for (int i = doclimit; i < warcFiles.size(); i++)
            warcFiles.removeFirst();

    long totalWarcFiles = warcFiles.size();
    LOG.info(totalWarcFiles + " many " + suffix + " files found under the docs path : " + docDir.toString());

    for (int i = 0; i < 2000; i++) {
        if (!warcFiles.isEmpty())
            executor.execute(new IndexerThread(writer, warcFiles.removeFirst()));
        else {
            if (!executor.isShutdown()) {
                Thread.sleep(30000);
                executor.shutdown();
            }
            break;
        }
    }

    long first = 0;
    //add some delay to let some threads spawn by scheduler
    Thread.sleep(30000);

    try {
        // Wait for existing tasks to terminate
        while (!executor.awaitTermination(1, TimeUnit.MINUTES)) {

            final long completedTaskCount = executor.getCompletedTaskCount();

            LOG.info(String.format("%.2f percentage completed",
                    (double) completedTaskCount / totalWarcFiles * 100.0d));

            if (!warcFiles.isEmpty())
                for (long i = first; i < completedTaskCount; i++) {
                    if (!warcFiles.isEmpty())
                        executor.execute(new IndexerThread(writer, warcFiles.removeFirst()));
                    else {
                        if (!executor.isShutdown())
                            executor.shutdown();
                    }
                }

            first = completedTaskCount;
            Thread.sleep(1000);
        }
    } catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        executor.shutdownNow();
        // Preserve interrupt status
        Thread.currentThread().interrupt();
    }

    if (totalWarcFiles != executor.getCompletedTaskCount())
        throw new RuntimeException("totalWarcFiles = " + totalWarcFiles
                + " is not equal to completedTaskCount =  " + executor.getCompletedTaskCount());

    int numIndexed = writer.maxDoc();

    try {
        writer.commit();
        if (optimize)
            writer.forceMerge(1);
    } finally {
        writer.close();
    }

    return numIndexed;
}

From source file:com.ebay.pulsar.metric.processor.MetricProcessor.java

@Override
public void sendEvent(JetstreamEvent event) throws EventException {
    incrementEventRecievedCounter();//from   ww w.ja v a 2  s.co  m
    String eventType = event.getEventType();

    Deque<DataPoint> dataByType = dataBuffer.get(eventType);
    if (dataByType == null) {
        dataByType = new ConcurrentLinkedDeque<DataPoint>();
        dataBuffer.put(eventType, dataByType);
    }

    Long currentTimestamp = System.currentTimeMillis();
    boolean isNewBatchOfEvents = false;

    if (dataByType.size() > 0
            && event.get("context_id") != dataByType.getLast().getEvents().peek().get("context_id"))
        isNewBatchOfEvents = true;

    //Flush old batchs
    if (isNewBatchOfEvents) {
        broadcastEventsByType(eventType, dataByType);
        incrementEventSentCounter();
    }

    if (dataByType.size() == 0 || isNewBatchOfEvents) {
        DataPoint dataPoint = new DataPoint(currentTimestamp);
        dataByType.add(dataPoint);
    }

    dataByType.getLast().addEvent(event);
    int maxLength = GENERIC_MAX_POINT;
    if (eventType.equalsIgnoreCase("MC_Metric") || eventType.equalsIgnoreCase("TwitterEventCount")) {
        maxLength = PAGE_VIEWS_POINT;
    }
    if (dataByType.size() > maxLength) {
        dataByType.removeFirst();
    }
}

From source file:cc.kave.commons.pointsto.analysis.unification.UnificationAnalysisVisitorContext.java

/**
 * Reruns the unification until all lazily added locations have propagated
 * and no more changes are detected./*from w  w w. j a va  2s. co m*/
 * 
 * {@link LocationIdentifier} are added lazily to
 * {@link ExtendedReferenceLocation} instances. If a location is added to an
 * already unified {@link ExtendedReferenceLocation}, the unification has to
 * be applied again to ensure correctness of the result.
 */
private void finalizePendingUnifications() {
    Deque<Pair<ReferenceLocation, ReferenceLocation>> worklist = new ArrayDeque<>();
    for (Map.Entry<ReferenceLocation, ReferenceLocation> locations : pendingUnifications.entries()) {
        ReferenceLocation refLoc1 = locations.getKey();
        ReferenceLocation refLoc2 = locations.getValue();

        int loc1Identifiers = refLoc1.getIdentifiers().size();
        int loc2Identifiers = refLoc2.getIdentifiers().size();

        if (loc1Identifiers != loc2Identifiers) {
            worklist.addFirst(ImmutablePair.of(refLoc1, refLoc2));
        }
    }

    while (!worklist.isEmpty()) {
        Pair<ReferenceLocation, ReferenceLocation> locations = worklist.removeFirst();
        ReferenceLocation loc1 = locations.getLeft();
        ReferenceLocation loc2 = locations.getRight();

        int previousIdentifiersLoc1 = loc1.getIdentifiers().size();
        int previousIdentifiersLoc2 = loc2.getIdentifiers().size();
        unify(loc1, loc2);

        updateUnificationWorklist(worklist, previousIdentifiersLoc1, loc1, loc2);
        updateUnificationWorklist(worklist, previousIdentifiersLoc2, loc2, loc1);
    }
}

From source file:de.interactive_instruments.ShapeChange.Target.ArcGISWorkspace.ArcGISWorkspace.java

private int establishEAPackageHierarchy(ClassInfo ci, int mainWorkspaceSubPkgId) throws EAException {

    // get path up to but not including the application schema package
    Deque<PackageInfo> pathToAppSchemaAsStack = new ArrayDeque<PackageInfo>();

    if (ci.pkg() != this.appSchemaPkg) {

        PackageInfo pkg = ci.pkg();//from   ww  w  .  java2s .  co m

        while (pkg != null && pkg != this.appSchemaPkg) {

            pathToAppSchemaAsStack.addFirst(pkg);

            pkg = pkg.owner();
        }
    }

    if (pathToAppSchemaAsStack.isEmpty()) {

        // class is situated in app schema package and thus shall be created
        // in main workspace sub-package
        return mainWorkspaceSubPkgId;

    } else {

        // walk down the path, create packages as needed

        Map<PackageInfo, Integer> eaPkgIdByModelPkg = eaPkgIdByModelPkg_byWorkspaceSubPkgId
                .get(mainWorkspaceSubPkgId);

        Integer eaParentPkgId = mainWorkspaceSubPkgId;
        Integer eaPkgId = null;

        while (!pathToAppSchemaAsStack.isEmpty()) {

            PackageInfo pi = pathToAppSchemaAsStack.removeFirst();

            if (eaPkgIdByModelPkg.containsKey(pi)) {

                eaPkgId = eaPkgIdByModelPkg.get(pi);

            } else {

                // create the EA package
                eaPkgId = EAModelUtil.createEAPackage(rep, pi, eaParentPkgId);
                eaPkgIdByModelPkg.put(pi, eaPkgId);
            }

            eaParentPkgId = eaPkgId;
        }

        return eaPkgId;
    }
}