Accueil / Java Techs / Groovy / Combine two lists in Groovy

Combine two lists in Groovy

Print Friendly, PDF & Email

Combination or concatenation of two or multiple lists are believed to appear quite frequently in programming. This article aims to show you how to union two lists in Groovy in different ways.

Combine lists with addAll

The java.util.ArrayList.addAll(Collection<? extends E> c)  method appends all of the elements from the specified collection (the second list) to the end of the current list (the first list), in the order that they are returned by the specified collection’s Iterator.

def fruits = ["Apple", "Banana", "Cherry"]
def newFruits = ["Pear", "Plum", "Strawberry"]
println fruits

The output looks like the following

[Apple, Banana, Cherry, Pear, Plum, Strawberry]

Combine lists using the plus operator

Naturally we can think about the plus operator when combining two lists. The plus operator will return a new list containing all the elements of the two lists while and the addAll  method appends the elements of the second list to the end of the first one.

def fruits = ["Apple", "Banana", "Cherry"]
def newFruits = ["Pear", "Plum", "Strawberry"]
println fruits + newFruits

Obviously, the output is the same as the one using addAll method.

I hope you could be interested in this useful article. If you have any queries, feel free to drop me a message underneath.

À propos Nguyen Vu Ngoc Tung

I love making new professional acquaintances. Don't hesitate to contact me via if you want to talk about information technology, education, and research on complex networks analysis (i.e., metabolic networks analysis), data analysis, and applications of graph theory. Specialties: researching and proposing innovative business approaches to organizations, evaluating and consulting about usability engineering, training and employee development, web technologies, software architecture.

Laisser une réponse

Votre adresse email ne sera pas publiéeLes champs requis sont surlignés *




Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.