1

I want to concatenate multiple lists with a single command, e.g. to do something like:

myFirstList.concat(mySecondList).concat(myThirdList);

or maybe

List.concat(myFirstList, mySecondList,myThirdList);

i.e. I'd like something like

List<T> concat(List<T> additional);

as a member of List (can't have that, I guess... :-( ), or

static <T> List<T> concat(List<T>... lists);

which is more doable. Does any package have this?

Note:

Yes, I know I can use addAll(), but that returns a boolean, so you can't use it repeatedly in the same command.

4

2 回答 2

1

Use addAll() method:

List<String> testList1 = new ArrayList<String>();           
testList1.add("one");
testList1.add("two");

List<String> testList2 = new ArrayList<String>();
testList2.add("three");

testList2.addAll(testList1);
//testList2 now has "three","one","two"
于 2013-01-14T11:59:48.163 回答
0

您可以使用该addAll方法并为此创建一个小型构建器:

class ListBuilder<T> {
    private List<T> list = new ArrayList<T>();

    public ListBuilder<T> concat(List<T> other) {
        this.list.addAll(other);
        return this;
    }

    public List<T> getAll() {
        return this.list;
    }
}

用法:

ListBuilder<String> builder = new ListBuilder<String>();
builder.concat(myFirstList).concat(mySecondList).concat(myThirdList);

System.out.println(builder.getAll());
于 2013-01-14T12:05:45.767 回答