public static <E> List<E> ensureImmutable(List<E> list) {
    if (list.isEmpty()) return Collections.emptyList();
    // Faster to make a copy than check the type to see if it is already a singleton list
    if (list.size() == 1) return Collections.singletonList(list.get(0));
    if (isImmutable(list)) return list;

    return Collections.unmodifiableList(new ArrayList<E>(list));
  }
@Test void ensureImmutable_convertsToSingletonList() {
    List<Object> list = new ArrayList<>();
    list.add("foo");
    assertThat(Lists.ensureImmutable(list).getClass().getSimpleName())
      .isEqualTo("SingletonList");
  }