Guava Collections之Immutable Collections,Sorted Collections

Immutable Collections :

public class ImmutableCollectionsTest
{

    @Test(expected = UnsupportedOperationException.class)
    public void testOf()
    {
        ImmutableList list = ImmutableList.of(1, 2, 3);
        assertThat(list, notNullValue());
        list.add(4);
        fail();
    }

    @Test
    public void testCopy()
    {
        Integer[] array = {1, 2, 3, 4, 5};
        System.out.println(ImmutableList.copyOf(array));
    }

    @Test
    public void testBuilder()
    {
        ImmutableList list = ImmutableList.builder()
                .add(1)
                .add(2, 3, 4).addAll(Arrays.asList(5, 6))
                .build();
        System.out.println(list);
    }

    @Test
    public void testImmutableMap()
    {
        ImmutableMap map = ImmutableMap.builder().put("Oracle", "12c")
                .put("Mysql", "7.0").build();
        System.out.println(map);
        try
        {
            map.put("Scala", "2.3.0");
            fail();
        } catch (Exception e)
        {
            assertThat(e instanceof UnsupportedOperationException, is(true));
        }
    }
}

Sorted Collections:

public class OrderingExampleTest
{

    @Test
    public void testJDKOrder()
    {
        List list = Arrays.asList(1, 5, 3, 8, 2);
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);
    }

    @Test(expected = NullPointerException.class)
    public void testJDKOrderIssue()
    {
        List list = Arrays.asList(1, 5, null, 3, 8, 2);
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);
    }

    @Test
    public void testOrderNaturalByNullFirst()
    {
        List list = Arrays.asList(1, 5, null, 3, 8, 2);
        Collections.sort(list, Ordering.natural().nullsFirst());
        System.out.println(list);
    }

    @Test
    public void testOrderNaturalByNullLast()
    {
        List list = Arrays.asList(1, 5, null, 3, 8, 2);
        Collections.sort(list, Ordering.natural().nullsLast());
        System.out.println(list);
    }

    @Test
    public void testOrderNatural()
    {
        List list = Arrays.asList(1, 5, 3, 8, 2);
        Collections.sort(list);
        assertThat(Ordering.natural().isOrdered(list), is(true));
    }


    @Test
    public void testOrderReverse()
    {
        List list = Arrays.asList(1, 5, 3, 8, 2);
        Collections.sort(list, Ordering.natural().reverse());
        System.out.println(list);
    }
}

你可能感兴趣的:(Guava Collections之Immutable Collections,Sorted Collections)