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

Setup

private List<String> firstHalfStates = Lists.newArrayList(
        "Alabama",
        "Alaska",
        "Arizona",
        "Arkansas",
        ...
        "Maryland",
        "Massachusetts",
        "Michigan",
        "Minnesota");

private List<String> secondHalfStates = Lists.newArrayList(
        "Mississippi",
        "Missouri",
        "Montana",
        ...
        "Washington",
        "West Virginia",
        "Wisconsin",
        "Wyoming");

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.

@Test
public void join_two_lists_in_java () {

    List<String> allStates = new ArrayList<String>(firstHalfStates);
    allStates.addAll(secondHalfStates);

    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.

@Test
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.

@Test
public void combine_two_lists_in_java_with_apache_commons () {

    @SuppressWarnings("unchecked")
    List<String> allStates = ListUtils.union(
            firstHalfStates,
            secondHalfStates);

    assertTrue(allStates.size() == 50);
}