码迷,mamicode.com
首页 > 编程语言 > 详细

Java 集合并交补

时间:2017-07-23 22:43:43      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:修改   ack   int   log   string   rem   copy   retain   print   

示例

package com.example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ListOpt {
    private List intersect(List ls1, List ls2) {
        List list = new ArrayList(Arrays.asList(new Object[ls1.size()]));
        Collections.copy(list, ls1);
        list.retainAll(ls2);
        return list;
    }

    private List union(List ls1, List ls2) {
        List list = new ArrayList(Arrays.asList(new Object[ls1.size()]));
        Collections.copy(list, ls1);
        list.addAll(ls2);
        return list;
    }

    private List diff(List ls1, List ls2) {
        List list = new ArrayList(Arrays.asList(new Object[ls1.size()]));
        Collections.copy(list, ls1);
        list.removeAll(ls2);
        return list;
    }

    public static void main(String[] args) {
        List<Integer> l1 = new ArrayList<Integer>() {{
            add(1);
            add(2);
            add(3);
        }};
        List<Integer> l2 = new ArrayList<Integer>() {{
            add(2);
            add(3);
            add(4);
        }};

        ListOpt opt = new ListOpt();
        List intersectList = opt.intersect(l1, l2);
        List union = opt.union(l1, l2);
        List diff = opt.diff(l1, l2);

        print(intersectList);
        print(union);
        print(diff);

    }

    private static void print(List lst) {
        if (lst.size() == 0) {
            return;
        }
        for (int i = 0; i <lst.size(); ++i) {
            System.out.println(lst.get(i));
        }
        System.out.println("---");
    }
}

输出

2
3
---
1
2
3
2
3
4
---
1
---

在操作之前对原对象进行了拷贝,如果对原对象直接操作会修改原来的对象

Java 集合并交补

标签:修改   ack   int   log   string   rem   copy   retain   print   

原文地址:http://www.cnblogs.com/kaituorensheng/p/7226085.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!