如何将多个迭代器合并为一个?

How to combine several iterators to one?

我可以 return 多个迭代器吗?例如,在 iterator() 方法中,也许我可以像这样组合迭代器?

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class Addresses implements Iterable<Address> {
    private final Address main;
    private final List<Address> additional;
    private final List<Address> verified;

    public Addresses(Address main, List<Address> additional, List<Address> verified) {
        this.main = main;
        this.additional = additional;
        this.verified = verified;
    }

    public Address getMain() {
        return main;
    }

    public List<Address> getAdditional() {
        return additional;
    }

    public List<Address> getVerified() {
        return verified;
    }

    @Override
    public Iterator<Address> iterator() {
        // return 3 iterators main and additional and verified like one?
        return additional.iterator() + verified.iterator() + Collections.singletonList(main).iterator();
    }

}

我只需要在一个循环中遍历两个列表和主地址中的所有项目,但将它们分开。例如,我将这样使用它

User user = ...
Addresses addresses = new Addresses(user.getMainAddress(), user.getAdditionalAddressess(), user.getVerifiedAddressess());
//iterate through addresses and change some fields an each address
user.setMain(addresses.getMain());
user.setAdditional(addresses.getAdditional());
user.setVerified(addresses.getVerified());

Guava有Iterators.concat,你看看。 link 可能包含你所有的答案。

使用Stream.concat,并从结果流中获取迭代器:

public Iterator<Address> iterator() {
    return Stream.concat(
        Stream.concat(additional.stream(), verified.stream()),
        Stream.of(main)).iterator();
}

请注意,如果有人在迭代器仍在使用时更改了附加地址或已验证地址,则结果是“未定义的”。你可以只在你的 class javadoc 中记录,或者你可以复制列表,这样你的方法提供了一个快照并且不受以后更改的影响:

public Iterator<Address> iterator() {
    Stream<String> additionalStream = new ArrayList<>(additional).stream();
    Stream<String> verifiedStream = new ArrayList<>(verified).stream();
    return Stream.concat(
        Stream.concat(additionalStream, verifiedStream),
        Stream.of(main)).iterator();
}