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.

cнŝdk
  • 28,676
  • 7
  • 47
  • 67
einpoklum
  • 86,754
  • 39
  • 223
  • 453
  • 1
    It doesn't chain but List has the method addAll. Is there really a need for this chaining ? – Denys Séguret Jan 14 '13 at 11:54
  • @dystroy: I didn't say there's a *need*. Obviously Java is Turing-complete without it... I'm looking for a convenience idiom. – einpoklum Jan 14 '13 at 13:14
  • The problem is that in order to have a coherent language/framework, you would have to do this with many many functions. That simply wasn't how the standard lib were designed. I don't say it's good as it is (java verbosity is painful) but having chaining ability just on one method only breaks the coherency and doesn't help. – Denys Séguret Jan 14 '13 at 13:17
  • @dystroy: But I'm not asking about the standard libraries necessarily. Guava doesn't have something like this, nor does Apache Commons.Collections. I ended up writing a small method myself but that doesn't sound like the Right Thing to do. – einpoklum Jan 14 '13 at 13:33

2 Answers2

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"
Eugenio Cuevas
  • 9,818
  • 1
  • 26
  • 48
0

You can use the addAll method and create a small builder for this:

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;
    }
}

Usage:

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

System.out.println(builder.getAll());
micha
  • 42,796
  • 15
  • 68
  • 78
  • 1
    Adding overhead just to make java look like another language doesn't seem, in my opinion, a good idea. This could be a pattern when building a whole new utility but not just for this. [not a critic of this answer but a general comment] – Denys Séguret Jan 14 '13 at 12:06