Example usage for java.util ArrayDeque add

List of usage examples for java.util ArrayDeque add

Introduction

In this page you can find the example usage for java.util ArrayDeque add.

Prototype

public boolean add(E e) 

Source Link

Document

Inserts the specified element at the end of this deque.

Usage

From source file:Main.java

public static void main(String[] args) {

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

    deque.add(3);
    deque.add(4);/*from   w  w w  .jav  a 2  s . com*/
    deque.add(25);
    deque.add(1);

    //iterator() is used to print all the elements
    //next() returns the next element on each iteration
    System.out.println("printing elements using iterator:");

    for (Iterator itr = deque.iterator(); itr.hasNext();) {
        System.out.println(itr.next());
    }

    //descendingIterator() is used to print the elements in reverse order
    //next() returns the next element on each iteration
    System.out.println("printing elements in reverse order:");

    for (Iterator descItr = deque.descendingIterator(); descItr.hasNext();) {
        System.out.println(descItr.next());
    }
}

From source file:Main.java

public static void main(String[] args) {

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

    deque.add(1);
    deque.add(2);/*from  w ww  . j  a  v  a  2  s  . c  om*/
    deque.add(10);
    deque.add(18);

    System.out.println(deque);

    // deque contains element 10
    boolean retval = deque.contains(10);

    if (retval == true) {
        System.out.println("element 10 is contained in the deque");
    } else {
        System.out.println("element 10 is not contained in the deque");
    }

    // deque does not contain element 25
    boolean retval2 = deque.contains(25);

    if (retval2 == true) {
        System.out.println("element 25 is contained in the deque");
    } else {
        System.out.println("element 25 is not contained in the deque");
    }
}

From source file:com.espertech.esper.dispatch.DispatchServiceImpl.java

private static void addToQueue(Dispatchable dispatchable, ArrayDeque<Dispatchable> dispatchQueue) {
    dispatchQueue.add(dispatchable);
}

From source file:name.abhijitsarkar.algorithms.core.Sorter.java

public static int[] bucketSort(int[] arr) {
    int[][] buckets = scatter(arr);

    ArrayDeque<int[]> stack = new ArrayDeque<int[]>();

    for (int[] bucket : buckets) {
        if (bucket != null) {
            stack.add(mergeSort(bucket));
        }//  w  w w  .  ja va  2s . co  m
    }

    return gather(stack);
}

From source file:io.selendroid.server.model.internal.AbstractNativeElementContext.java

/** visible for testing */
protected static List<AndroidElement> searchViews(AbstractNativeElementContext context, List<View> roots,
        Predicate predicate, boolean findJustOne) {
    List<AndroidElement> elements = new ArrayList<AndroidElement>();
    if (roots == null || roots.isEmpty()) {
        return elements;
    }/*w  ww  .ja v  a2s.c o  m*/
    ArrayDeque<View> queue = new ArrayDeque<View>();

    for (View root : roots) {
        queue.add(root);
        while (!queue.isEmpty()) {
            View view = queue.pop();
            if (predicate.apply(view)) {
                elements.add(context.newAndroidElement(view));
                if (findJustOne) {
                    break;
                }
            }
            if (view instanceof ViewGroup) {
                ViewGroup group = (ViewGroup) view;
                int childrenCount = group.getChildCount();
                for (int index = 0; index < childrenCount; index++) {
                    queue.add(group.getChildAt(index));
                }
            }
        }
    }
    return elements;
}

From source file:name.abhijitsarkar.algorithms.core.Sorter.java

private static int[] gather(ArrayDeque<int[]> stack) {
    int[] mergedBucket = null;

    while (!stack.isEmpty()) {
        mergedBucket = stack.remove();/*ww  w .  j a  v  a2s .com*/

        if (!stack.isEmpty()) {
            int[] bucket = stack.remove();

            mergedBucket = merge(mergedBucket, bucket);

            stack.add(mergedBucket);
        }
    }

    return mergedBucket;
}

From source file:com.espertech.esper.core.context.util.StatementAgentInstanceUtil.java

private static void evaluateEventForStatementInternal(EPServicesContext servicesContext, EventBean theEvent,
        List<AgentInstance> agentInstances) {
    // context was created - reevaluate for the given event
    ArrayDeque<FilterHandle> callbacks = new ArrayDeque<FilterHandle>(2);
    servicesContext.getFilterService().evaluate(theEvent, callbacks); // evaluates for ALL statements
    if (callbacks.isEmpty()) {
        return;/* w  w  w. j  ava  2 s  . c  o m*/
    }

    // there is a single callback and a single context, if they match we are done
    if (agentInstances.size() == 1 && callbacks.size() == 1) {
        AgentInstance agentInstance = agentInstances.get(0);
        if (agentInstance.getAgentInstanceContext().getStatementId()
                .equals(callbacks.getFirst().getStatementId())) {
            process(agentInstance, servicesContext, callbacks, theEvent);
        }
        return;
    }

    // use the right sorted/unsorted Map keyed by AgentInstance to sort
    boolean isPrioritized = servicesContext.getConfigSnapshot().getEngineDefaults().getExecution()
            .isPrioritized();
    Map<AgentInstance, Object> stmtCallbacks;
    if (!isPrioritized) {
        stmtCallbacks = new HashMap<AgentInstance, Object>();
    } else {
        stmtCallbacks = new TreeMap<AgentInstance, Object>(AgentInstanceComparator.INSTANCE);
    }

    // process all callbacks
    for (FilterHandle filterHandle : callbacks) {
        // determine if this filter entry applies to any of the affected agent instances
        String statementId = filterHandle.getStatementId();
        AgentInstance agentInstanceFound = null;
        for (AgentInstance agentInstance : agentInstances) {
            if (agentInstance.getAgentInstanceContext().getStatementId().equals(statementId)) {
                agentInstanceFound = agentInstance;
                break;
            }
        }
        if (agentInstanceFound == null) { // when the callback is for some other stmt
            continue;
        }

        EPStatementHandleCallback handleCallback = (EPStatementHandleCallback) filterHandle;
        EPStatementAgentInstanceHandle handle = handleCallback.getAgentInstanceHandle();

        // Self-joins require that the internal dispatch happens after all streams are evaluated.
        // Priority or preemptive settings also require special ordering.
        if (handle.isCanSelfJoin() || isPrioritized) {
            Object stmtCallback = stmtCallbacks.get(agentInstanceFound);
            if (stmtCallback == null) {
                stmtCallbacks.put(agentInstanceFound, handleCallback);
            } else if (stmtCallback instanceof ArrayDeque) {
                ArrayDeque<EPStatementHandleCallback> q = (ArrayDeque<EPStatementHandleCallback>) stmtCallback;
                q.add(handleCallback);
            } else {
                ArrayDeque<EPStatementHandleCallback> q = new ArrayDeque<EPStatementHandleCallback>(4);
                q.add((EPStatementHandleCallback) stmtCallback);
                q.add(handleCallback);
                stmtCallbacks.put(agentInstanceFound, q);
            }
            continue;
        }

        // no need to be sorted, process
        process(agentInstanceFound, servicesContext, Collections.<FilterHandle>singletonList(handleCallback),
                theEvent);
    }

    if (stmtCallbacks.isEmpty()) {
        return;
    }

    // Process self-join or sorted prioritized callbacks
    for (Map.Entry<AgentInstance, Object> entry : stmtCallbacks.entrySet()) {
        AgentInstance agentInstance = entry.getKey();
        Object callbackList = entry.getValue();
        if (callbackList instanceof ArrayDeque) {
            process(agentInstance, servicesContext, (Collection<FilterHandle>) callbackList, theEvent);
        } else {
            process(agentInstance, servicesContext,
                    Collections.<FilterHandle>singletonList((FilterHandle) callbackList), theEvent);
        }
        if (agentInstance.getAgentInstanceContext().getEpStatementAgentInstanceHandle().isPreemptive()) {
            return;
        }
    }
}

From source file:com.espertech.esper.view.std.MergeView.java

public final Iterator<EventBean> iterator() {
    // The merge data view has multiple parent views which are AddPropertyValueView
    ArrayDeque<Iterable<EventBean>> iterables = new ArrayDeque<Iterable<EventBean>>();

    for (View dataView : parentViews) {
        iterables.add(dataView);
    }/*  ww  w  .  ja va  2 s .c o m*/

    return new IterablesListIterator(iterables);
}

From source file:gobblin.ingestion.google.webmaster.CollectionEquals.java

/**
 * Test the GoogleWebmasterExtractorIterator to make sure that it first gets all pages based on the filters
 * and then for each page, it asks for the queries.
 * @throws IOException/*w  w w. j  av  a  2  s  . c  o  m*/
 */
@Test
public void testIterator() throws IOException {
    GoogleWebmasterDataFetcher client = Mockito.mock(GoogleWebmasterDataFetcher.class);
    String country = "USA";
    String date = "2016-11-01";
    ArrayList<GoogleWebmasterFilter.Dimension> requestedDimensions = new ArrayList<>();
    ArrayList<GoogleWebmasterDataFetcher.Metric> requestedMetrics = new ArrayList<>();

    ArrayDeque<ProducerJob> allJobs = new ArrayDeque<>();
    String page1 = siteProperty + "a/1";
    String page2 = siteProperty + "b/1";
    allJobs.add(new SimpleProducerJob(page1, date, date));
    allJobs.add(new SimpleProducerJob(page2, date, date));
    Mockito.when(client.getAllPages(eq(date), eq(date), eq(country), eq(GoogleWebmasterClient.API_ROW_LIMIT)))
            .thenReturn(allJobs);

    //Set performSearchAnalyticsQuery Mock1
    String[] a1 = { "r1-c1", "r1-c2" };
    List<String[]> results1 = new ArrayList<>();
    results1.add(a1);
    List<ApiDimensionFilter> filters1 = new ArrayList<>();
    filters1.add(GoogleWebmasterFilter.countryEqFilter(country));
    filters1.add(GoogleWebmasterFilter.pageFilter(GoogleWebmasterFilter.FilterOperator.EQUALS, page1));
    Mockito.when(client.performSearchAnalyticsQuery(eq(date), eq(date), eq(GoogleWebmasterClient.API_ROW_LIMIT),
            eq(requestedDimensions), eq(requestedMetrics), argThat(new CollectionEquals(filters1))))
            .thenReturn(results1);

    //Set performSearchAnalyticsQuery Mock2
    String[] a2 = { "r2-c1", "r2-c2" };
    List<String[]> results2 = new ArrayList<>();
    results2.add(a2);
    List<ApiDimensionFilter> filters2 = new ArrayList<>();
    filters2.add(GoogleWebmasterFilter.countryEqFilter(country));
    filters2.add(GoogleWebmasterFilter.pageFilter(GoogleWebmasterFilter.FilterOperator.EQUALS, page2));
    Mockito.when(client.performSearchAnalyticsQuery(eq(date), eq(date), eq(5000), eq(requestedDimensions),
            eq(requestedMetrics), argThat(new CollectionEquals(filters2)))).thenReturn(results2);

    Map<GoogleWebmasterFilter.Dimension, ApiDimensionFilter> map = new HashMap<>();
    map.put(GoogleWebmasterFilter.Dimension.COUNTRY, GoogleWebmasterFilter.countryEqFilter(country));
    WorkUnitState defaultState = GoogleWebmasterExtractorTest.getWorkUnitState1();
    defaultState.setProp(GoogleWebMasterSource.KEY_QUERIES_TUNING_BATCH_SIZE, 1);
    GoogleWebmasterExtractorIterator iterator = new GoogleWebmasterExtractorIterator(client, date, date,
            requestedDimensions, requestedMetrics, map, defaultState);

    List<String[]> response = new ArrayList<>();
    response.add(iterator.next());
    response.add(iterator.next());
    Assert.assertTrue(!iterator.hasNext());
    Assert.assertTrue(response.contains(a1));
    Assert.assertTrue(response.contains(a2));

    Mockito.verify(client, Mockito.times(1)).getAllPages(eq(date), eq(date), eq(country), eq(5000));
    Mockito.verify(client, Mockito.times(1)).performSearchAnalyticsQuery(eq(date), eq(date), eq(5000),
            eq(requestedDimensions), eq(requestedMetrics), argThat(new CollectionEquals(filters1)));
    Mockito.verify(client, Mockito.times(1)).performSearchAnalyticsQuery(eq(date), eq(date), eq(5000),
            eq(requestedDimensions), eq(requestedMetrics), argThat(new CollectionEquals(filters2)));
}

From source file:com.offbynull.peernetic.playground.chorddht.model.SuccessorTable.java

/**
 * Updates this successor table so that the immediate successor is {@code successor} and the successors after it are {@code table}. If
 * {@code table} contains the base pointer in it, all pointers including and after the base pointer won't be added. If {@code table}'s
 * size exceeds the number of bits in base pointer's id, it'll be trimmed so that it doesn't exceed. The pointers in {@code table} must
 * be sorted. The point at which {@code table} loops around our base id is the point that it'll be trimmed.
 * @param successor immediate successor/*from w ww.ja  v  a 2  s.  c o  m*/
 * @param table successors after {@code successor}
 * @throws NullPointerException if any arguments are {@code null} or contain {@code null}
 * @throws IllegalArgumentException if {@code successor}'s id has a different limit bit size than the base pointer's id, or if the ids
 * of any of the pointers in {@code table} have a different limit bit size than the base pointer's id
 */
public void update(Pointer successor, List<Pointer> table) {
    Validate.notNull(successor);
    Validate.noNullElements(table);

    Id baseId = basePtr.getId();
    Id successorId = successor.getId();

    Validate.isTrue(IdUtils.getBitLength(successorId) == limit);

    if (table.size() > limit) {
        table = table.subList(0, limit);
    }

    Id lastId = successor.getId();
    int lastTableIdx = -1;
    int idx = 0;
    for (Pointer ptrSuccessor : table) {
        Id ptrSuccessorId = ptrSuccessor.getId();

        Validate.isTrue(IdUtils.getBitLength(ptrSuccessorId) == limit);

        if (baseId.equals(ptrSuccessorId)) {
            lastTableIdx = idx;
            break;
        }

        if (Id.comparePosition(baseId, ptrSuccessorId, lastId) <= 0) {
            lastTableIdx = idx;
            break;
        }

        lastId = ptrSuccessor.getId();

        idx++;
    }

    if (lastTableIdx != -1) {
        table = table.subList(0, lastTableIdx);
    }

    int len = table.size() + 1;
    ArrayDeque<Pointer> newTable = new ArrayDeque<>(len);

    newTable.add(successor);
    table.forEach(x -> {
        Id id = x.getId();
        if (id.equals(baseId)) {
            newTable.add(new InternalPointer(id)); // if referencing self, use internalpointer
        } else {
            newTable.add(x);
        }
    });

    this.table = newTable;
}