Canonical toList in java?

Is there something similar in any standard library (e.g. apache-commons, guava)?

public static <T> List<T> toList(Iterable<T> iterable) {
    if (iterable instanceof List)
        return (List<T>)iterable;

    if (iterable instanceof Collection)
        return new ArrayList<T>((Collection<T>)iterable);

    List<T> result = new ArrayList<T>();
    for (T item : iterable)
        result.add(item);

    return result;
}
+3
source share
1 answer

I don’t think so, because your implementation does two completely different things:

  • If the argument is a list, it returns it. Thus, the returned list will be a live representation of the argument. Changes in each of the lists are visible in the other.
  • If the argument is not a list, it returns a copy of it. The returned list is independent of the argument.

The two things are so different that no sane general purpose library drops them together in one way.

+9
source

Source: https://habr.com/ru/post/1777162/


All Articles