欢迎光临
我们一直在努力

Java中合并两个list的三种方式

java.jpg

这里介绍三种合并两个list的方式:

package org.4spaces;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.commons.collections.ListUtils;

import java.util.ArrayList;
import java.util.List;

public class JoinTwoList {
    public static void main(String[] args) {
        List<String> firstHalf = Lists.newArrayList("四个空格-www.4spaces.org", "微言电影-www.weiyandy.com", "中国健康在线-www.chinahol.com");
        List<String> secondHalf = Lists.newArrayList("微言资讯-www.weiyanzixun.com");
        new JoinTwoList().joinWithJava(firstHalf, secondHalf);
        new JoinTwoList().joinWithGuava(firstHalf, secondHalf);
        new JoinTwoList().joinWithApache(firstHalf, secondHalf);
    }

    /**
     * 1.直接使用Java
     */
    public void joinWithJava(List<String> firstHalf, List<String> secondHalf) {
        List<String> allSites = new ArrayList<>(firstHalf);
        allSites.addAll(secondHalf);
        System.out.println(allSites.size() + "---" + allSites.get(3));
    }

    /**
     * 2.使用Google guava
     */
    public void joinWithGuava(List<String> firstHalf, List<String> secondHalf) {
        List<String> allSites = Lists.newArrayList(Iterables.concat(firstHalf, secondHalf));
        System.out.println(allSites.size() + "---" + allSites.get(3));
    }

    /**
     * 3.使用Apache Commons
     */
    public void joinWithApache(List<String> firstHalf, List<String> secondHalf) {
        List<String> allSites = ListUtils.union(firstHalf, secondHalf);
        System.out.println(allSites.size() + "---" + allSites.get(3));
    }
}
赞(0)
未经允许不得转载:Ddmit » Java中合并两个list的三种方式

评论 抢沙发

登录

找回密码

注册