欢迎光临
感受代码之美

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));
    }
}
转载请注明来源:四个空格 » Java中合并两个list的三种方式

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址