Guava collections -- Lists

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012410733/article/details/51855227

Guava全文介绍地址:Google Guava
这次主要介绍是的是com.google.common.collect.Lists.主要的作用是就与java List相关的静态的实用方法。在Guava中与之类似的还有Sets,Maps以及Queues这些类。
下面就介绍一个Lists的主要用法:

1、对List进行切割

    @Test
    public void testPartition() {
        List<Integer> numbers = Lists.newArrayList(1, 2, 3, 4);
        List<List<Integer>> subLists = Lists.partition(numbers, 2);
        List<Integer> s1 = Lists.newArrayList(1, 2);
        List<Integer> s2 = Lists.newArrayList(3, 4);
        assertThat(subLists.get(0), is(s1));
        assertThat(subLists.get(1), is(s2));
    }

2、对List进行反转

    @Test
    public void testReverse() {
        List<Integer> numbers = Lists.newArrayList(1, 2, 3, 4);
        List<Integer> expected = Lists.newArrayList(4, 3, 2, 1);
        List<Integer> reversed = Lists.reverse(numbers);
        assertThat(expected, is(reversed));
    }

3、进List进行转换

    @Test
    public void testGainNameForUser() throws Exception {
        User user1 = User.builder().idCard(1L).gender(1).name("carl").build();
        User user2 = User.builder().idCard(2L).gender(2).name("erin").build();
        User user3 = User.builder().idCard(3L).gender(1).name("kevin").build();
        List<User> users = Lists.newArrayList(user1, user2, user3);
        List<String> names = Lists.transform(users, new Function<User, String>() {
            @Override
            public String apply(User input) {
                return input.getName();
            }
        });
        assertThat(names, is(Lists.newArrayList("carl", "erin", "kevin")));
    }

更多功能等待你的发现。

阅读更多

没有更多推荐了,返回首页