Java Code Examples for java.util.Deque#descendingIterator()

The following examples show how to use java.util.Deque#descendingIterator() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExtraLanguageFeatureNameConverter.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies if the pattern matches the given identifier.
 *
 * @param feature the feature to test.
 * @return {@code true} if the pattern matches.
 */
public boolean matches(Deque<String> feature) {
	boolean match;
	if (this.rawFeature != null) {
		match = this.rawFeature.equals(feature.getLast());
	} else {
		final Matcher featureMatcher = this.featurePattern.matcher(feature.getLast());
		match = featureMatcher.matches();
	}
	if (match && this.pathPatterns.length > 0) {
		final Iterator<String> iterator = feature.descendingIterator();
		// Skip last
		iterator.next();
		for (int j = this.pathPatterns.length - 1;
				match && iterator.hasNext() && j >= 0;
				--j) {
			final String component = iterator.next();
			final Pattern pathPattern = this.pathPatterns[j];
			final Matcher pathMatcher = pathPattern.matcher(component);
			match = pathMatcher.matches();
		}
	}
	return match;
}
 
Example 2
Source File: ConcurrentArrayListTest.java    From threadly with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void descendingIteratorTest() {
  Deque<String> comparisionDeque = new LinkedList<>();
  for (int i = 0; i < TEST_QTY; i++) {
    String str = Integer.toString(i);
    comparisionDeque.addLast(str);
    testList.add(str);
  }
  
  Iterator<String> clIt = comparisionDeque.descendingIterator();
  Iterator<String> testIt = testList.descendingIterator();
  while (clIt.hasNext()) {
    assertTrue(testIt.hasNext());
    assertEquals(clIt.next(), testIt.next());
  }
}
 
Example 3
Source File: ThreadsStatsCollector.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private Integer getTrailingAverage(Deque<Entry<Long, Long>> list, int seconds) {
  Entry<Long,Long> latest = list.peekLast();
  Entry<Long,Long> old = list.peekFirst();
  Iterator<Entry<Long,Long>> iter = list.descendingIterator();
  while (iter.hasNext()) {
    Entry<Long,Long> e = iter.next();
    if (e.getKey() - latest.getKey() > seconds * ONE_BILLION) {
      old = e;
      break;
    }
  }

  final long oldKey = old.getKey();
  final long latestKey = latest.getKey();
  if (oldKey == latestKey) {
    return null;
  } else {
    return (int) (100 * (old.getValue() - latest.getValue()) / (oldKey - latestKey));
  }
}
 
Example 4
Source File: YamlProperties.java    From neodymium-library with MIT License 6 votes vote down vote up
/**
 * Build us a property key from the current state on the stack
 *
 * @param state
 *            the stack
 * @return a property key
 */
private String buildKey(final Deque<String> state)
{
    final Iterator<String> i = state.descendingIterator();

    final StringBuilder sb = new StringBuilder(64);
    while (i.hasNext())
    {
        if (sb.length() > 0)
        {
            sb.append('.');
        }
        sb.append(i.next());
    }

    return sb.toString();
}
 
Example 5
Source File: ChorusLine.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void run(Deque<Integer> deq) {
    while (deq.size() > 1) {
        Iterator<Integer> it = deq.iterator();
        it.next(); it.remove();
        it = deq.descendingIterator();
        it.next(); it.remove();
    }
    System.out.println(deq);
}
 
Example 6
Source File: ReflectiveMessageValidator.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
protected String createPathString(Deque<Object> accessorStack) {
	StringBuilder result = new StringBuilder("$");
	Iterator<Object> resultIter = accessorStack.descendingIterator();
	while(resultIter.hasNext()) {
		Object accessor = resultIter.next();
		if (accessor instanceof Method)
			result.append('.').append(getPropertyName((Method) accessor));
		else if (accessor instanceof Integer)
			result.append('[').append(accessor).append(']');
		else
			result.append(accessor);
	}
	return result.toString();
}
 
Example 7
Source File: BaseGenericObjectPool.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
/**
 * Create an EvictionIterator for the provided idle instance deque.
 * @param idleObjects underlying deque
 */
EvictionIterator(final Deque<PooledObject<T>> idleObjects) {
    this.idleObjects = idleObjects;

    if (getLifo()) {
        idleObjectIterator = idleObjects.descendingIterator();
    } else {
        idleObjectIterator = idleObjects.iterator();
    }
}
 
Example 8
Source File: ExpressionReducer.java    From doma with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitCommaOperatorNode(CommaOperatorNode node, Deque<ExpressionNode> p) {
  for (Iterator<ExpressionNode> it = p.descendingIterator(); it.hasNext(); ) {
    node.addNode(it.next());
    it.remove();
  }
  return null;
}
 
Example 9
Source File: BaseGenericObjectPool.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Create an EvictionIterator for the provided idle instance deque.
 * @param idleObjects underlying deque
 */
EvictionIterator(final Deque<PooledObject<T>> idleObjects) {
    this.idleObjects = idleObjects;

    if (getLifo()) {
        idleObjectIterator = idleObjects.descendingIterator();
    } else {
        idleObjectIterator = idleObjects.iterator();
    }
}
 
Example 10
Source File: BuildChainBuilder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void cycleCheck(BuildStepBuilder builder, Set<BuildStepBuilder> visited, Set<BuildStepBuilder> checked,
        final Map<BuildStepBuilder, Set<Produce>> dependencies, final Deque<Produce> producedPath)
        throws ChainBuildException {
    if (!checked.contains(builder)) {
        if (!visited.add(builder)) {
            final StringBuilder b = new StringBuilder("Cycle detected:\n\t\t   ");
            final Iterator<Produce> itr = producedPath.descendingIterator();
            if (itr.hasNext()) {
                Produce produce = itr.next();
                for (;;) {
                    b.append(produce.getStepBuilder().getBuildStep());
                    ItemId itemId = produce.getItemId();
                    b.append(" produced ").append(itemId);
                    b.append("\n\t\tto ");
                    if (!itr.hasNext())
                        break;
                    produce = itr.next();
                    if (produce.getStepBuilder() == builder)
                        break;
                }
                b.append(builder.getBuildStep());
            }
            throw new ChainBuildException(b.toString());
        }
        try {
            final Set<Produce> dependencySet = dependencies.getOrDefault(builder, Collections.emptySet());
            cycleCheckProduce(dependencySet, visited, checked, dependencies, producedPath);
        } finally {
            visited.remove(builder);
        }
    }
    checked.add(builder);
}
 
Example 11
Source File: Collection8Test.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Various ways of traversing a collection yield same elements
 */
public void testTraversalEquivalence() {
    Collection c = impl.emptyCollection();
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    int n = rnd.nextInt(6);
    for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
    ArrayList iterated = new ArrayList();
    ArrayList iteratedForEachRemaining = new ArrayList();
    ArrayList tryAdvanced = new ArrayList();
    ArrayList spliterated = new ArrayList();
    ArrayList splitonced = new ArrayList();
    ArrayList forEached = new ArrayList();
    ArrayList streamForEached = new ArrayList();
    ConcurrentLinkedQueue parallelStreamForEached = new ConcurrentLinkedQueue();
    ArrayList removeIfed = new ArrayList();
    for (Object x : c) iterated.add(x);
    c.iterator().forEachRemaining(iteratedForEachRemaining::add);
    for (Spliterator s = c.spliterator();
         s.tryAdvance(tryAdvanced::add); ) {}
    c.spliterator().forEachRemaining(spliterated::add);
    {                       // trySplit returns "strict prefix"
        Spliterator s1 = c.spliterator(), s2 = s1.trySplit();
        if (s2 != null) s2.forEachRemaining(splitonced::add);
        s1.forEachRemaining(splitonced::add);
    }
    c.forEach(forEached::add);
    c.stream().forEach(streamForEached::add);
    c.parallelStream().forEach(parallelStreamForEached::add);
    c.removeIf(e -> { removeIfed.add(e); return false; });
    boolean ordered =
        c.spliterator().hasCharacteristics(Spliterator.ORDERED);
    if (c instanceof List || c instanceof Deque)
        assertTrue(ordered);
    HashSet cset = new HashSet(c);
    assertEquals(cset, new HashSet(parallelStreamForEached));
    if (ordered) {
        assertEquals(iterated, iteratedForEachRemaining);
        assertEquals(iterated, tryAdvanced);
        assertEquals(iterated, spliterated);
        assertEquals(iterated, splitonced);
        assertEquals(iterated, forEached);
        assertEquals(iterated, streamForEached);
        assertEquals(iterated, removeIfed);
    } else {
        assertEquals(cset, new HashSet(iterated));
        assertEquals(cset, new HashSet(iteratedForEachRemaining));
        assertEquals(cset, new HashSet(tryAdvanced));
        assertEquals(cset, new HashSet(spliterated));
        assertEquals(cset, new HashSet(splitonced));
        assertEquals(cset, new HashSet(forEached));
        assertEquals(cset, new HashSet(streamForEached));
        assertEquals(cset, new HashSet(removeIfed));
    }
    if (c instanceof Deque) {
        Deque d = (Deque) c;
        ArrayList descending = new ArrayList();
        ArrayList descendingForEachRemaining = new ArrayList();
        for (Iterator it = d.descendingIterator(); it.hasNext(); )
            descending.add(it.next());
        d.descendingIterator().forEachRemaining(
            e -> descendingForEachRemaining.add(e));
        Collections.reverse(descending);
        Collections.reverse(descendingForEachRemaining);
        assertEquals(iterated, descending);
        assertEquals(iterated, descendingForEachRemaining);
    }
}
 
Example 12
Source File: ASTWriter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private static void enqueueChildren(final Node node, final Class<?> nodeClass, final List<Field> children) {
    final Deque<Class<?>> stack = new ArrayDeque<>();

    /**
     * Here is some ugliness that can be overcome by proper ChildNode annotations
     * with proper orders. Right now we basically sort all classes up to Node
     * with super class first, as this often is the natural order, e.g. base
     * before index for an IndexNode.
     *
     * Also there are special cases as this is not true for UnaryNodes(lhs) and
     * BinaryNodes extends UnaryNode (with lhs), and TernaryNodes.
     *
     * TODO - generalize traversal with an order built on annotations and this
     * will go away.
     */
    Class<?> clazz = nodeClass;
    do {
        stack.push(clazz);
        clazz = clazz.getSuperclass();
    } while (clazz != null);

    if (node instanceof TernaryNode) {
        // HACK juggle "third"
        stack.push(stack.removeLast());
    }
    // HACK change operator order for BinaryNodes to get lhs first.
    final Iterator<Class<?>> iter = node instanceof BinaryNode ? stack.descendingIterator() : stack.iterator();

    while (iter.hasNext()) {
        final Class<?> c = iter.next();
        for (final Field f : c.getDeclaredFields()) {
            try {
                f.setAccessible(true);
                final Object child = f.get(node);
                if (child == null) {
                    continue;
                }

                if (child instanceof Node) {
                    children.add(f);
                } else if (child instanceof Collection) {
                    if (!((Collection<?>)child).isEmpty()) {
                        children.add(f);
                    }
                }
            } catch (final IllegalArgumentException | IllegalAccessException e) {
                return;
            }
        }
    }
}
 
Example 13
Source File: ASTWriter.java    From nashorn with GNU General Public License v2.0 4 votes vote down vote up
private static void enqueueChildren(final Node node, final Class<?> nodeClass, final List<Field> children) {
    final Deque<Class<?>> stack = new ArrayDeque<>();

    /**
     * Here is some ugliness that can be overcome by proper ChildNode annotations
     * with proper orders. Right now we basically sort all classes up to Node
     * with super class first, as this often is the natural order, e.g. base
     * before index for an IndexNode.
     *
     * Also there are special cases as this is not true for UnaryNodes(lhs) and
     * BinaryNodes extends UnaryNode (with lhs), and TernaryNodes.
     *
     * TODO - generalize traversal with an order built on annotations and this
     * will go away.
     */
    Class<?> clazz = nodeClass;
    do {
        stack.push(clazz);
        clazz = clazz.getSuperclass();
    } while (clazz != null);

    if (node instanceof TernaryNode) {
        // HACK juggle "third"
        stack.push(stack.removeLast());
    }
    // HACK change operator order for BinaryNodes to get lhs first.
    final Iterator<Class<?>> iter = node instanceof BinaryNode ? stack.descendingIterator() : stack.iterator();

    while (iter.hasNext()) {
        final Class<?> c = iter.next();
        for (final Field f : c.getDeclaredFields()) {
            try {
                f.setAccessible(true);
                final Object child = f.get(node);
                if (child == null) {
                    continue;
                }

                if (child instanceof Node) {
                    children.add(f);
                } else if (child instanceof Collection) {
                    if (!((Collection<?>)child).isEmpty()) {
                        children.add(f);
                    }
                }
            } catch (final IllegalArgumentException | IllegalAccessException e) {
                return;
            }
        }
    }
}
 
Example 14
Source File: FileObjectCrawler.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static boolean isLink(
    @NonNull final FileObject file,
    @NonNull final Deque<? extends FileObject> path,
    @NullAllowed final Stats stats) {
    final long st = System.currentTimeMillis();
    boolean hasLink = false;
    try {
        final Iterator<? extends FileObject> it = path.descendingIterator();
        while (it.hasNext()) {
            final FileObject pathElement = it.next();
            if (file.getNameExt().equals(pathElement.getNameExt())) {
                try {
                    if (mockLinkTypes != null ?
                        mockLinkTypes.get(Pair.<FileObject,FileObject>of(pathElement, file)) :
                        isSameFile(file, pathElement)) {
                        hasLink = true;
                        break;
                    }
                } catch (IOException ioe) {
                    LOG.log(
                        Level.INFO,
                        "Cannot convert to cannonical files {0} and {1}",   //NOI18N
                        new Object[]{
                            file,
                            pathElement
                        });
                    LOG.log(
                        Level.FINE,
                        null,
                        ioe);
                    break;
                }
            }
        }
        return hasLink;
    } finally {
        long et = System.currentTimeMillis();
        if (stats != null) {
            stats.linkCheckTime+= (et-st);
            if (hasLink) {
                stats.linkCount++;
            }
        }
    }
}
 
Example 15
Source File: ASTWriter.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private static void enqueueChildren(final Node node, final Class<?> nodeClass, final List<Field> children) {
    final Deque<Class<?>> stack = new ArrayDeque<>();

    /**
     * Here is some ugliness that can be overcome by proper ChildNode annotations
     * with proper orders. Right now we basically sort all classes up to Node
     * with super class first, as this often is the natural order, e.g. base
     * before index for an IndexNode.
     *
     * Also there are special cases as this is not true for UnaryNodes(lhs) and
     * BinaryNodes extends UnaryNode (with lhs), and TernaryNodes.
     *
     * TODO - generalize traversal with an order built on annotations and this
     * will go away.
     */
    Class<?> clazz = nodeClass;
    do {
        stack.push(clazz);
        clazz = clazz.getSuperclass();
    } while (clazz != null);

    if (node instanceof TernaryNode) {
        // HACK juggle "third"
        stack.push(stack.removeLast());
    }
    // HACK change operator order for BinaryNodes to get lhs first.
    final Iterator<Class<?>> iter = node instanceof BinaryNode ? stack.descendingIterator() : stack.iterator();

    while (iter.hasNext()) {
        final Class<?> c = iter.next();
        for (final Field f : c.getDeclaredFields()) {
            try {
                f.setAccessible(true);
                final Object child = f.get(node);
                if (child == null) {
                    continue;
                }

                if (child instanceof Node) {
                    children.add(f);
                } else if (child instanceof Collection) {
                    if (!((Collection<?>)child).isEmpty()) {
                        children.add(f);
                    }
                }
            } catch (final IllegalArgumentException | IllegalAccessException e) {
                return;
            }
        }
    }
}
 
Example 16
Source File: ASTWriter.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static void enqueueChildren(final Node node, final Class<?> nodeClass, final List<Field> children) {
    final Deque<Class<?>> stack = new ArrayDeque<>();

    /**
     * Here is some ugliness that can be overcome by proper ChildNode annotations
     * with proper orders. Right now we basically sort all classes up to Node
     * with super class first, as this often is the natural order, e.g. base
     * before index for an IndexNode.
     *
     * Also there are special cases as this is not true for UnaryNodes(lhs) and
     * BinaryNodes extends UnaryNode (with lhs), and TernaryNodes.
     *
     * TODO - generalize traversal with an order built on annotations and this
     * will go away.
     */
    Class<?> clazz = nodeClass;
    do {
        stack.push(clazz);
        clazz = clazz.getSuperclass();
    } while (clazz != null);

    if (node instanceof TernaryNode) {
        // HACK juggle "third"
        stack.push(stack.removeLast());
    }
    // HACK change operator order for BinaryNodes to get lhs first.
    final Iterator<Class<?>> iter = node instanceof BinaryNode ? stack.descendingIterator() : stack.iterator();

    while (iter.hasNext()) {
        final Class<?> c = iter.next();
        for (final Field f : c.getDeclaredFields()) {
            try {
                f.setAccessible(true);
                final Object child = f.get(node);
                if (child == null) {
                    continue;
                }

                if (child instanceof Node) {
                    children.add(f);
                } else if (child instanceof Collection) {
                    if (!((Collection<?>)child).isEmpty()) {
                        children.add(f);
                    }
                }
            } catch (final IllegalArgumentException | IllegalAccessException e) {
                return;
            }
        }
    }
}
 
Example 17
Source File: ASTWriter.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private static void enqueueChildren(final Node node, final Class<?> nodeClass, final List<Field> children) {
    final Deque<Class<?>> stack = new ArrayDeque<>();

    /**
     * Here is some ugliness that can be overcome by proper ChildNode annotations
     * with proper orders. Right now we basically sort all classes up to Node
     * with super class first, as this often is the natural order, e.g. base
     * before index for an IndexNode.
     *
     * Also there are special cases as this is not true for UnaryNodes(lhs) and
     * BinaryNodes extends UnaryNode (with lhs), and TernaryNodes.
     *
     * TODO - generalize traversal with an order built on annotations and this
     * will go away.
     */
    Class<?> clazz = nodeClass;
    do {
        stack.push(clazz);
        clazz = clazz.getSuperclass();
    } while (clazz != null);

    if (node instanceof TernaryNode) {
        // HACK juggle "third"
        stack.push(stack.removeLast());
    }
    // HACK change operator order for BinaryNodes to get lhs first.
    final Iterator<Class<?>> iter = node instanceof BinaryNode ? stack.descendingIterator() : stack.iterator();

    while (iter.hasNext()) {
        final Class<?> c = iter.next();
        for (final Field f : c.getDeclaredFields()) {
            try {
                f.setAccessible(true);
                final Object child = f.get(node);
                if (child == null) {
                    continue;
                }

                if (child instanceof Node) {
                    children.add(f);
                } else if (child instanceof Collection) {
                    if (!((Collection<?>)child).isEmpty()) {
                        children.add(f);
                    }
                }
            } catch (final IllegalArgumentException | IllegalAccessException e) {
                return;
            }
        }
    }
}
 
Example 18
Source File: ASTWriter.java    From jdk8u_nashorn with GNU General Public License v2.0 4 votes vote down vote up
private static void enqueueChildren(final Node node, final Class<?> nodeClass, final List<Field> children) {
    final Deque<Class<?>> stack = new ArrayDeque<>();

    /**
     * Here is some ugliness that can be overcome by proper ChildNode annotations
     * with proper orders. Right now we basically sort all classes up to Node
     * with super class first, as this often is the natural order, e.g. base
     * before index for an IndexNode.
     *
     * Also there are special cases as this is not true for UnaryNodes(lhs) and
     * BinaryNodes extends UnaryNode (with lhs), and TernaryNodes.
     *
     * TODO - generalize traversal with an order built on annotations and this
     * will go away.
     */
    Class<?> clazz = nodeClass;
    do {
        stack.push(clazz);
        clazz = clazz.getSuperclass();
    } while (clazz != null);

    if (node instanceof TernaryNode) {
        // HACK juggle "third"
        stack.push(stack.removeLast());
    }
    // HACK change operator order for BinaryNodes to get lhs first.
    final Iterator<Class<?>> iter = node instanceof BinaryNode ? stack.descendingIterator() : stack.iterator();

    while (iter.hasNext()) {
        final Class<?> c = iter.next();
        for (final Field f : c.getDeclaredFields()) {
            try {
                f.setAccessible(true);
                final Object child = f.get(node);
                if (child == null) {
                    continue;
                }

                if (child instanceof Node) {
                    children.add(f);
                } else if (child instanceof Collection) {
                    if (!((Collection<?>)child).isEmpty()) {
                        children.add(f);
                    }
                }
            } catch (final IllegalArgumentException | IllegalAccessException e) {
                return;
            }
        }
    }
}
 
Example 19
Source File: Collection8Test.java    From streamsupport with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Various ways of traversing a collection yield same elements
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(dataProvider = "Source")
public void testTraversalEquivalence(String description, Supplier<CollectionImplementation> sci) {
    CollectionImplementation impl = sci.get();
    Collection c = impl.emptyCollection();
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    int n = rnd.nextInt(6);
    for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
    ArrayList iterated = new ArrayList();
    ArrayList iteratedForEachRemaining = new ArrayList();
    ArrayList tryAdvanced = new ArrayList();
    ArrayList spliterated = new ArrayList();
    ArrayList splitonced = new ArrayList();
    ArrayList forEached = new ArrayList();
    ArrayList streamForEached = new ArrayList();
    ConcurrentLinkedQueue parallelStreamForEached = new ConcurrentLinkedQueue();
    ArrayList removeIfed = new ArrayList();
    for (Object x : c) iterated.add(x);
    Iterators.forEachRemaining(c.iterator(), iteratedForEachRemaining::add);
    for (Spliterator s = Spliterators.spliterator(c);
         s.tryAdvance(tryAdvanced::add); ) {}
    Spliterators.spliterator(c).forEachRemaining(spliterated::add);
    {                       // trySplit returns "strict prefix"
        Spliterator<?> s1 = Spliterators.spliterator(c), s2 = s1.trySplit();
        if (s2 != null) s2.forEachRemaining(splitonced::add);
        s1.forEachRemaining(splitonced::add);
    }
    Iterables.forEach(c, forEached::add);
    StreamSupport.stream(c).forEach(streamForEached::add);
    StreamSupport.parallelStream(c).forEach(parallelStreamForEached::add);
    Iterables.removeIf(c, e -> { removeIfed.add(e); return false; });
    boolean ordered =
        Spliterators.spliterator(c).hasCharacteristics(Spliterator.ORDERED);
    if (c instanceof List || c instanceof Deque)
        assertTrue(ordered);
    HashSet<?> cset = new HashSet<>(c);
    assertEquals(cset, new HashSet<>(parallelStreamForEached));
    if (ordered) {
        assertEquals(iterated, iteratedForEachRemaining);
        assertEquals(iterated, tryAdvanced);
        assertEquals(iterated, spliterated);
        assertEquals(iterated, splitonced);
        assertEquals(iterated, forEached);
        assertEquals(iterated, streamForEached);
        assertEquals(iterated, removeIfed);
    } else {
        assertEquals(cset, new HashSet<>(iterated));
        assertEquals(cset, new HashSet<>(iteratedForEachRemaining));
        assertEquals(cset, new HashSet<>(tryAdvanced));
        assertEquals(cset, new HashSet<>(spliterated));
        assertEquals(cset, new HashSet<>(splitonced));
        assertEquals(cset, new HashSet<>(forEached));
        assertEquals(cset, new HashSet<>(streamForEached));
        assertEquals(cset, new HashSet<>(removeIfed));
    }
    if (c instanceof Deque) {
        Deque<?> d = (Deque<?>) c;
        ArrayList descending = new ArrayList();
        ArrayList descendingForEachRemaining = new ArrayList();
        for (Iterator<?> it = d.descendingIterator(); it.hasNext(); )
            descending.add(it.next());
        Iterators.forEachRemaining(d.descendingIterator(),
            e -> descendingForEachRemaining.add(e));
        Collections.reverse(descending);
        Collections.reverse(descendingForEachRemaining);
        assertEquals(iterated, descending);
        assertEquals(iterated, descendingForEachRemaining);
    }
}
 
Example 20
Source File: ASTWriter.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private static void enqueueChildren(final Node node, final Class<?> nodeClass, final List<Field> children) {
    final Deque<Class<?>> stack = new ArrayDeque<>();

    /**
     * Here is some ugliness that can be overcome by proper ChildNode annotations
     * with proper orders. Right now we basically sort all classes up to Node
     * with super class first, as this often is the natural order, e.g. base
     * before index for an IndexNode.
     *
     * Also there are special cases as this is not true for UnaryNodes(lhs) and
     * BinaryNodes extends UnaryNode (with lhs), and TernaryNodes.
     *
     * TODO - generalize traversal with an order built on annotations and this
     * will go away.
     */
    Class<?> clazz = nodeClass;
    do {
        stack.push(clazz);
        clazz = clazz.getSuperclass();
    } while (clazz != null);

    if (node instanceof TernaryNode) {
        // HACK juggle "third"
        stack.push(stack.removeLast());
    }
    // HACK change operator order for BinaryNodes to get lhs first.
    final Iterator<Class<?>> iter = node instanceof BinaryNode ? stack.descendingIterator() : stack.iterator();

    while (iter.hasNext()) {
        final Class<?> c = iter.next();
        for (final Field f : c.getDeclaredFields()) {
            try {
                f.setAccessible(true);
                final Object child = f.get(node);
                if (child == null) {
                    continue;
                }

                if (child instanceof Node) {
                    children.add(f);
                } else if (child instanceof Collection) {
                    if (!((Collection<?>)child).isEmpty()) {
                        children.add(f);
                    }
                }
            } catch (final IllegalArgumentException | IllegalAccessException e) {
                return;
            }
        }
    }
}