Skip to content

Instantly share code, notes, and snippets.

@sureshnath
Last active December 16, 2015 08:08
Show Gist options
  • Save sureshnath/5403215 to your computer and use it in GitHub Desktop.
Save sureshnath/5403215 to your computer and use it in GitHub Desktop.
Collection Util isEmpty ImmutableList Java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.util.List;
public class CollectionUtil {
public static <T> List<T> getImmutableNonNullList(List<T> list) {
return isEmpty(list) ? ImmutableList.<T>of() : ImmutableList.copyOf(list);
}
public static <T> boolean isEmpty(Iterable<?> iterable) {
return iterable == null || Iterables.isEmpty(iterable);
}
}
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class CollectionUtilTest {
@Test
public void testNullList() {
List<String> expected = ImmutableList.<String>of();
List<String> actual = CollectionUtil.getImmutableNonNullList(null);
Assert.assertEquals("expecting empty immutable instance", expected, actual);
}
@Test
public void testEmptyList() {
List<String> expected = ImmutableList.<String>of();
List<String> actual = CollectionUtil.getImmutableNonNullList(expected);
Assert.assertEquals("expecting empty immutable instance", expected, actual);
}
@Test
public void testMutableList() {
List<String> mutableList = Lists.newArrayList("test1", "test2");
ImmutableList<String> expected = ImmutableList.copyOf(mutableList);
List<String> actual = CollectionUtil.getImmutableNonNullList(expected);
Assert.assertEquals("expecting immutable list", expected, actual);
}
@Test
public void testImmutableList() {
ImmutableList<String> expected = ImmutableList.of("test1", "test2");
List<String> actual = CollectionUtil.getImmutableNonNullList(expected);
Assert.assertEquals("expecting immutable list", expected, actual);
}
/**
* Test of isEmpty method, of class CollectionUtil.
*/
@Test
public void testIsEmpty() {
Assert.assertTrue("should be true", CollectionUtil.isEmpty(null));
Assert.assertTrue("should be true", CollectionUtil.isEmpty(ImmutableList.<String>of()));
Assert.assertFalse("should be false", CollectionUtil.isEmpty(ImmutableList.<String>of("test")));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment