Search code examples
javaapache-commonsutilityutility-method

Is there a utility method for creating a list with specified size and contents?


public static <T> List<T> repeat(T contents, int length) {
    List<T> list = new ArrayList<T>();
    for (int i = 0; i < length; i++) {
        list.add(contents);
    }
    return list;
}

This is a utility method in our proprietary commons libraries. It's useful for creating lists. For example, I might want a list of 68 question marks for generating a large SQL query. This lets you do that in one line of code, instead of four lines of code.

Is there a utility class somewhere in java/apache-commons which already does this? I browsed ListUtils, CollectionUtils, Arrays, Collections, pretty much everything I could think of but I can't find it anywhere. I don't like keeping generic utility methods in my code, if possible, since they're usually redundant with apache libraries.


Solution

  • The Collections utility class will help you:

    list = Collections.nCopies(length,contents);
    

    or if you want a mutable list:

    list = new ArrayList<T>(Collections.nCopies(length,contents));
               // or whatever List implementation you want.