使用来自不同 Iterator / Iterable 的值创建 Iterable

Creating an Iterable with values from a different Iterator / Iterable

我写了一个 ADT 排序二叉树,函数如下:

public Iterator<T> getInorderIterator(){
    return new InorderIterator();
}

有效,按顺序遍历树。

然后我有一个字典 class,它使用这个 class 来存储类型 Entry<K, V> 的条目,以及一个 return 所有条目的 Iterable 的函数。

public Iterable<Entry<K, V>> entries() {
    //bST is BinarySortedTree
    return () -> bST.getInorderIterator();
}

所有这些都按预期工作,但我想再写 2 个函数,return 是字典中键和值的 Iterable。我将如何从 entries() 的 Iterable returned 或在 BinaryTree 上调用 getInorderIterator() 创建这些 Iterables。

条目class:

public class Entry<K, V> {
    public final K key;
    public final V value;

    public Entry(K key, V value) {
        this.key = key;
        this.value = value;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Entry) {
            Entry other = (Entry)o;
            return this.key.equals(other.key) && this.value.equals(other.value);
        }
        return false;
    }
}

我不能在 BinaryTree class 中编写迭代器,因为它使用抽象数据类型。

只需使用标准库,您就可以做到

StreamSupport.stream(entries().spliterator(), false).map(entry -> entry.value).iterator()

对于值(键的明显变化)。不知道Java9和10有没有更简单的方法

Apache Collection Commons

IteratorUtils.transformedIterator(bST.getInorderIterator(), entry -> entry.value)