Join two lists

Similar to joining two arrays, this example will demonstrate how to combine two lists into a single arraylist using java, guava and apache commons. For each snippet, we have broken all U.S. states into two lists which we will combine into one. In a related example we demonstrate how to join two lists in groovy.

groovy join lists


private List<String> firstHalfStates = Lists.newArrayList(
private List<String> secondHalfStates = Lists.newArrayList(
        "West Virginia",

Straight up Java

Using straight up java, we will initialize the arraylist by passing firstHalfStates into the constructor then call Lists.addAll which appends all of the elements at the end of the list in the order by the specified collection.

public void join_two_lists_in_java () {

    List<String> allStates = new ArrayList<String>(firstHalfStates);
    assertTrue(allStates.size() == 50);        

Google Guava

Using guava, we will initialize the list by calling Lists.newArrayList and passing in the result of Iterables.concat which combines both arraylists into one iterable.

public void combine_two_lists_in_java_with_guava () {

    List<String> allStates = Lists.newArrayList(
            Iterables.concat(firstHalfStates, secondHalfStates));
    assertTrue(allStates.size() == 50);

Apache Commons

Apache commons ListUtils provide a series of utility method for List instances. We will call ListUtils.union which will append the the second list to the first list.

public void combine_two_lists_in_java_with_apache_commons () {
    List<String> allStates = ListUtils.union(
    assertTrue(allStates.size() == 50);