简体   繁体   English

一个集合,表示Java中两个集合的串联

[英]A collection that represents a concatenation of two collections in Java

Is there a class that represents the concatenation of a collection with another collection? 是否有一个类表示集合与另一个集合的串联? This class should be a Collection in itself, and should delegate all methods to the underlying (inner) collections - no extra memory should be allocated, nor any of the original collections modified. 这个类本身应该是一个Collection,并且应该将所有方法委托给底层(内部)集合 - 不应该分配额外的内存,也不应该修改任何原始集合。

Example usage: 用法示例:

Collection<String> foo = ...
Collection<String> bar = ...

// this should be O(1) memory and time
Collection<String> combined = concat(foo, bar);

if (combined.contains("Zee"))
  ...

for (String str : combined)
  System.out.println(str);

As always for any collections stuff, look at google-collections . 与任何收藏品一样,请查看google-collections If you have Set s, specifically (not just a general collection), you want: 如果您有Set ,特别是(不仅仅是一般集合),您需要:

Set<String> combined = Sets.union(foo, bar);

which creates an unmodifiable view of the two sets. 这会创建两组的不可修改的视图。 That is, changes in foo or bar will be reflected in combined (but combined.add() etc is not supported). 也就是说, foobar变化将反映在combined (但不支持combined.add()等)。

For the more generic case, you have Iterables.concat() but that merely lets you iterate over the joined item, the Iterable interface obviously doesn't include contains so you're a little hosed there. 对于更通用的情况,你有Iterables.concat()但只是让你迭代连接的项目, Iterable接口显然不包含contains所以你有点在那里。

The other collections utilities classes in google-collections ( com.google.common.collect.Lists and com.google.common.collect.Collections2 ) don't contain any concatenation methods. google-collections中的其他集合实用程序类( com.google.common.collect.Listscom.google.common.collect.Collections2 )不包含任何串联方法。 Don't see why they couldn't, but at the moment they don't. 不明白为什么他们不能,但目前他们不这样做。

Your question is very vague. 你的问题非常模糊。 Especially "with another item another collection" is quite unclear. 特别是“与另一个项目另一个集合”是非常不清楚的。

You can at least add the contents of another Collection to the current Collection using Collection#addAll() . 您至少可以使用Collection#addAll()将另一个Collection的内容添加到当前Collection Here Collection can be anything of its subinterfaces/implementations, eg List or Set . 这里Collection可以是其子接口/实现的任何内容,例如ListSet

Example: 例:

List<String> foos = Arrays.asList("foo1", "foo2", "foo3");
List<String> bars = Arrays.asList("bar1", "bar2", "bar3");
foos.addAll(bars); // Now foos contains everything.

Edit : Or do you actually want to create a new Collection based on an existing Collection and then add a new item to it? 编辑 :还是你真的想创建一个新的 Collection基于现有的Collection ,然后添加一个新的项目呢? In this case just construct a new Collection with the existing Collection as constructor argument. 在这种情况下,只需使用现有的Collection作为构造函数参数构造一个新的Collection Eg: 例如:

List<String> foos = Arrays.asList("foo1", "foo2", "foo3");
List<String> bars = new ArrayList<String>(foos);
bars.add("bar"); // Now bars contains everything.

There is not, but writing it yourself should be straight forward 没有,但自己写作应该是直截了当的

package ch.akuhn.util;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Concat {

    public static <T> Iterable<T> all(final Iterable<T>... iterables) {
        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                return new Iterator<T>() {
                    Iterator<Iterable<T>> more = Arrays.asList(iterables).iterator();
                    Iterator<T> current = more.hasNext() ? more.next().iterator() : null;
                    @Override
                    public boolean hasNext() {
                        if (current == null) return false;
                        if (current.hasNext()) return true;
                        current = more.hasNext() ? more.next().iterator() : null;
                        return this.hasNext();
                    }

                    @Override
                    public T next() {
                        if (!hasNext()) throw new NoSuchElementException();
                        return current.next();
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }

}

And then 然后

for (Object each: Concat.all(collection,whatever,etcetera,...)) {
    // ...
}

Just wrote this code here, compile at your own risk! 刚刚在这里编写了这段代码,编译风险自负!

PS, if you gonna write unit tests for this class, send 'em to me. PS, 如果你要为这堂课编写单元测试,请发送给我。

I think what you're asking for is a Java construct that allows you to put collections together without modifying the original collections. 我认为你所要求的是一个Java结构,它允许你将集合放在一起而不需要修改原始集合。 In other words, you have collections A and B, both of size N and M respectively. 换句话说,您有集合A和B,分别为N和M. After the concat call, you still have collections A and B and their sizes are still N and M, however you have collection C as well which points to A and B, making its size N+M. 在连续调用之后,你仍然有集合A和B,它们的大小仍然是N和M,但是你也有集合C,它指向A和B,使其大小为N + M.

The answer is no, Java doesn't have anything out of the box that does this... However you could write a quick wrapper that wraps a series of collections and add those collections to it. 答案是否定的,Java没有任何开箱即用的功能......但是你可以编写一个快速包装器来包装一系列集合并将这些集合添加到它。 (All it would do is maintain references to each of the collections) and you could expose get/insert methods as needed. (它只会维护对每个集合的引用)并且您可以根据需要公开get / insert方法。

Apache Commons Collections还有一个更通用的CompositeCollection类,可以用作任意数量Collection的接口。

I'm not sure what your asking. 我不确定你的要求。 My interpretation of your question is that your looking for the add method on the Collection. 我对你的问题的解释是你在Collection上寻找add方法。 I don't think that's what you're asking though. 我不认为这是你问的问题。

尝试InterleavingEnumeration或apache的commons集合' ListUtils (ListUtils.union())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM