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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With