How do I inject collections using list element in Spring?

The following example show you how to use the <list> element to wire collection property. We can use it to wire property of either arrays or some implementation of java.util.Collection such as java.util.ArrayList.

For this example we will create a bean called Album that have a collection of Song beans in it. So here is our bean classes.

package org.kodejava.spring.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class Album {
    private String title;
    private int year;
    private List<Song> songs = new ArrayList<>();
    private Map<String, Publisher> publisher = new HashMap<>();
    private Properties props = new Properties();

    public Album() {
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public void setSongs(List<Song> songs) {
        this.songs = songs;
    }

    public void setPublisher(Map<String, Publisher> publisher) {
        this.publisher = publisher;
    }

    public void setProps(Properties props) {
        this.props = props;
    }

    @Override
    public String toString() {
        return "Album{" +
                "title='" + title + '\'' +
                ", year=" + year +
                ", songs=" + songs +
                ", publisher=" + publisher +
                ", props=" + props +
                '}';
    }
}
package org.kodejava.spring.core;

public class Song {
    private String title;
    private String writer;

    public Song() {
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setWriter(String writer) {
        this.writer = writer;
    }

    @Override
    public String toString() {
        return "Song{" +
                "title='" + title + '\'' +
                ", writer='" + writer + '\'' +
                '}';
    }
}
package org.kodejava.spring.core;

public class Publisher {
    private String name;

    public Publisher() {
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Publisher{" +
                "name=" + name +
                '}';
    }
}

Here is the Spring configuration file, CollectionList.xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="song1" class="org.kodejava.spring.core.Song">
        <property name="title" value="I Saw Her Standing There" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song2" class="org.kodejava.spring.core.Song">
        <property name="title" value="Misery" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song3" class="org.kodejava.spring.core.Song">
        <property name="title" value="Anna (Go to Him)" />
        <property name="writer" value="Beatles" />
    </bean>


    <bean id="album" class="org.kodejava.spring.core.Album">
        <property name="title" value="Please Please Me" />
        <property name="year" value="1963" />
        <property name="songs">
            <list>
                <ref bean="song1" />
                <ref bean="song2" />
                <ref bean="song3" />
            </list>
        </property>
    </bean>

</beans>

The part of the configuration that wire the song collection is inside the album bean. You can see that we have a property name songs. This property has a <list> element that contains a couple <ref> elements referring to some Song type beans.

Now let’s run it with the following code:

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoList {
    public static void main(String[] args) {
        var context = new ClassPathXmlApplicationContext("collection-list.xml");

        Album album = (Album) context.getBean("album");
        System.out.println("Album = " + album);
        context.close();
    }
}

You’ll see the following output when you run the program:

Album = Album{title='Please Please Me', year=1963, songs=[Song{title='I Saw Her Standing There', writer='Beatles'}, Song{title='Misery', writer='Beatles'}, Song{title='Anna (Go to Him)', writer='Beatles'}], publisher={}, props={}}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I inject collections properties in Spring?

Beside injecting a simple value (using the value attribute) and a reference to other bean (using the ref attribute). We can also inject collections properties into a bean.

Spring provides four ways to inject collections. There are <list> and <set> that can be used to inject arrays or any implementation of java.util.Collection. The <map> that can be used to inject property of type java.util.Map. And the <props> can be used to inject property of type java.util.Properties.

Here is a table that summarize the collection configuration support in Spring.

Collection Element Description
<list> Wiring a list of values, where the values might have duplicates.
<set> Wiring a set of values, where the values can not have duplicates.
<map> Wiring a key-value pairs collection, where the key and value can be any type
<props> Wiring a key-value pairs property, where the key and value are both type of String

You can see the following example on how to use each type of this collection configuration:

How do I convert collections into JSON?

This example show you how to convert Java collections object into JSON string. For Student class use in this example you can find it the previous example on How do I convert object into JSON?.

package org.kodejava.gson;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.kodejava.gson.support.Student;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CollectionToJson {
    public static void main(String[] args) {
        // Converts a collection of string object into JSON string.
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Carol");
        names.add("Mallory");

        Gson gson = new Gson();
        String jsonNames = gson.toJson(names);
        System.out.println("jsonNames = " + jsonNames);

        // Converts a collection Student object into JSON string
        Student a = new Student("Alice", "Apple St", getDOB(2000, 10, 1));
        Student b = new Student("Bob", "Banana St", null);
        Student c = new Student("Carol", "Grape St", getDOB(2000, 5, 21));
        Student d = new Student("Mallory", "Mango St", null);

        List<Student> students = new ArrayList<>();
        students.add(a);
        students.add(b);
        students.add(c);
        students.add(d);

        gson = new Gson();
        String jsonStudents = gson.toJson(students);
        System.out.println("jsonStudents = " + jsonStudents);

        // Converts JSON string into a collection of Student object.
        Type type = new TypeToken<List<Student>>() {
        }.getType();
        List<Student> studentList = gson.fromJson(jsonStudents, type);

        for (Student student : studentList) {
            System.out.println("student.getName() = " + student.getName());
        }
    }

    private static Date getDOB(int year, int month, int date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DATE, date);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }
}

Here is the result of our program:

jsonNames = ["Alice","Bob","Carol","Mallory"]
jsonStudents = [{"name":"Alice","address":"Apple St","dateOfBirth":"Oct 1, 2000, 12:00:00 AM"},{"name":"Bob","address":"Banana St"},{"name":"Carol","address":"Grape St","dateOfBirth":"May 21, 2000, 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}]
student.getName() = Alice
student.getName() = Bob
student.getName() = Carol
student.getName() = Mallory

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

Maven Central

How do I create type specific collections?

package org.kodejava.basic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TypeSpecificCollection {
    public static void main(String[] args) {
        // Using a Generic can enable us to create a type specific collection
        // object. In the example below we create a Map whose key is an Integer
        // a have the value of a String.
        Map<Integer, String> grades = new HashMap<>();
        grades.put(1, "A");
        grades.put(2, "B");
        grades.put(3, "C");
        grades.put(4, "D");
        grades.put(5, "E");

        // A value obtained from type specific collection doesn't need to
        // be cast, it knows the type returned.
        String value = grades.get(1);
        System.out.println("value = " + value);

        // Creating a List that will contain a String only values.
        List<String> dayNames = new ArrayList<>();
        dayNames.add("Sunday");
        dayNames.add("Monday");
        dayNames.add("Tuesday");
        dayNames.add("Wednesday");

        // We also don't need to cast the retrieved value because it knows the
        // returned type object.
        String firstDay = dayNames.get(0);
        System.out.println("firstDay = " + firstDay);
    }
}

How do I use for-each in Java?

Using for-each command to iterate arrays or a list can simplified our code. Below is an example how to do it in Java. The first loop is for iterating array and the second for iterating a list containing a some names.

package org.kodejava.lang;

import java.util.ArrayList;
import java.util.List;

public class ForEachExample {
    public static void main(String[] args) {
        Integer[] numbers = {10, 100, 1000, 10000, 100000, 1000000};

        for (Integer i : numbers) {
            System.out.println("Number: " + i);
        }

        List<String> names = new ArrayList<>();
        names.add("Musk");
        names.add("Nakamoto");
        names.add("Einstein");

        for (String name : names) {
            System.out.println("Name: " + name);
        }
    }
}

The result of the code snippet:

Number: 10
Number: 100
Number: 1000
Number: 10000
Number: 100000
Number: 1000000
Name: Musk
Name: Nakamoto
Name: Einstein

How do I convert Array to Collection?

package org.kodejava.util;

import java.util.Arrays;
import java.util.List;

public class ArrayToListExample {
    public static void main(String[] args) {
        // Creates an array of object, in this case we create an
        // Integer array.
        Integer[] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};

        // Convert the created array above to collection, in this
        // example we convert it to a List.
        List<Integer> list = Arrays.asList(numbers);

        // We've got a list of our array here and iterate it.
        for (Integer number : list) {
            System.out.print(number + ", ");
        }
    }
}

How do I convert collection to ArrayList?

package org.kodejava.util;

import java.util.ArrayList;
import java.util.LinkedList;

public class CollectionToArrayList {
    public static void main(String[] args) {
        // We create LinkedList collection type at put some values
        // in it. Here we put A, B, C and D letter into it.
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.push("A");
        linkedList.push("B");
        linkedList.push("C");
        linkedList.push("D");

        // Let say you want to convert it to other type of collection,
        // for instance here we convert it into ArrayList. To do it
        // we can pass the collection created above as a parameter to
        // ArrayList constructor.
        ArrayList<String> arrayList = new ArrayList<>(linkedList);

        // Now we have converted the collection into ArrayList and
        // printed what is inside.
        for (String s : arrayList) {
            System.out.println("s = " + s);
        }
    }
}

How do I create an empty collection object?

Sometimes you need to return an empty collection from your Java methods. The java.util.Collections utility class have three different static constants for creating empty List, Set and Map.

  • Collections.EMPTY_LIST
  • Collections.EMPTY_SET
  • Collections.EMPTY_MAP

There are also methods when you want to create type-safe empty collections.

  • Collections.emptyList()
  • Collections.emptySet()
  • Collections.emptyMap()

Bellow it the code example.

package org.kodejava.util;

import java.util.*;

public class EmptyCollectionDemo {
    public static void main(String[] args) {
        List list = Collections.EMPTY_LIST;
        System.out.println("list.size()  = " + list.size());
        Set set = Collections.EMPTY_SET;
        System.out.println("set.size()   = " + set.size());
        Map map = Collections.EMPTY_MAP;
        System.out.println("map.size()   = " + map.size());

        // For the type-safe example use the following methods.
        List<String> strings = Collections.emptyList();
        System.out.println("strings.size = " + strings.size());

        Set<Long> longs = Collections.emptySet();
        System.out.println("longs.size() = " + longs.size());

        Map<String, Date> dates = Collections.emptyMap();
        System.out.println("dates.size() = " + dates.size());
    }
}

The output are:

list.size()  = 0
set.size()   = 0
map.size()   = 0
strings.size = 0
longs.size() = 0
dates.size() = 0

How do I convert a collection object into an array?

To convert collection-based object into an array we can use toArray() or toArray(T[] a) method provided by the implementation of Collection interface such as java.util.ArrayList.

package org.kodejava.util;

import java.util.List;
import java.util.ArrayList;

public class CollectionToArrayExample {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        words.add("Kode");
        words.add("Java");
        words.add("-");
        words.add("Learn");
        words.add("Java");
        words.add("by");
        words.add("Examples");

        String[] array = words.toArray(new String[0]);
        for (String word : array) {
            System.out.println(word);
        }
    }
}

Our code snippet result is shown below:

Kode
Java
-
Learn
Java
by
Examples

How do I convert an array into a collection object?

To convert array based data into List / Collection based we can use java.util.Arrays class. This class provides a static method asList(T... a) that converts array into List / Collection.

package org.kodejava.util;

import java.util.Arrays;
import java.util.List;

public class ArrayAsListExample {
    public static void main(String[] args) {
        String[] words = {"Happy", "New", "Year", "2021"};
        List<String> list = Arrays.asList(words);

        for (String word : list) {
            System.out.println(word);
        }
    }
}

The results of our code are:

Happy
New
Year
2021