38

I'm looking for a static method in the Java core libraries or some other commonly used dependency — preferably one of Apache — that does the following:

public static <T> Collection<T> wrap(final T object){
    final Collection<T> collection = new ArrayList<T>();
    collection.add(object);
    return collection;
}

Do you know where such a method already exists? Since I guess the problem is common, I don't want to duplicate it's solution.

Kerat
  • 1,074
  • 9
  • 15

5 Answers5

68

java.util.Collections.singleton(object) will give you an immutable Set. singletonList is also available.

Less efficiently java.util.Arrays.asList(object) will give you a mutable (can use list.set(0, x);), but non-structurally changeable (can't add or remove) List. It is a bit more expensive as there is an extra array that is created client-side.

Tom Hawtin - tackline
  • 143,103
  • 30
  • 210
  • 299
14

Here are some efficient ways to wrap Java object(s) in List, as of Java 8.

Collections.singletonList: Single item, immutable, since 1.3.
Collections.singletonList( object )
High performance backed by internal class.

Collections.nCopies: One object, zero to many items, immutable, since 1.2.
Collections.nCopies( number_of_copy, object )
High performance backed by internal class. All items point to same object.

Array.asList: Any number of objects, size immutable (individual elements mutable), since 1.2.
Arrays.asList( object1, object2, object3 )
Backed by internal class. Items are converted to array at compile time and this array directly backs the List.

new ArrayList(Collection): Any number of objects, mutable, since 1.2
new ArrayList<>( Arrays.asList( object1, object2, object3 ) )
The ArrayList is created with an array clone and an array copy, and so does not use any loops.

Yann39
  • 11,418
  • 10
  • 50
  • 76
Sheepy
  • 16,528
  • 4
  • 44
  • 67
2

Immutable list in guava

public static <E> ImmutableList<E> of(E element)

Returns an immutable list containing a single element. This list behaves and performs comparably to Collections.singleton(T), but will not accept a null element. It is preferable mainly for consistency and maintainability of your code.

NimChimpsky
  • 44,999
  • 57
  • 192
  • 304
1

Don't be afraid of writing something yourself. As far as I know it doesn't exist. I think a reason for this is that the utility method decides which implementation of Collection it uses. In your case you chose for ArrayList, but there are a whole bunch of other collections.

Martijn Courteaux
  • 65,802
  • 45
  • 192
  • 282
1

java.util.Collections.singletonList() or singleton(). Note though that the result is immutable.

sharakan
  • 6,741
  • 1
  • 32
  • 61