数组的交集用法

来源:互联网 发布:天猫整站j2ee源码下载 编辑:程序博客网 时间:2024/06/06 04:14

假设希望找出两个集交集,即两个集中共有的元素,首先建立两个新集,接着调用retainAll()方法。

import java.util.ArrayList;public class Test {    public Test() {        // TODO Auto-generated constructor stub    }    public static void main(String[] args) {        // TODO Auto-generated method stub        ArrayList<Integer> a1=new ArrayList<Integer>();        a1.add(1);        a1.add(2);        a1.add(3);        a1.add(4);        ArrayList<Integer> a2=new ArrayList<Integer>();        a2.add(2);        a2.add(3);        a2.add(4);        a2.add(5);        a1.retainAll(a2);//retainAll()方法仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作)        for(Integer i:a1){            System.out.println(i);        }    }}

输出结果

234

可以将这个思路向前推进一步。例如,假如有一个映射表,将员工的ID映射为员工对象,并且建立了一个将要结束聘用期的所有员工的ID集。

Map<String,Employee> staffMap=...Set<String> terminatedIDs=...

直接建立一个键集,并删除终止聘用关系的所有员工即可。

staffMap.keySet().removeAll(terminatedIDs);

由于键集是映射表的一个视图,所以,键与对应的员工将会从映射表中自动地删除。

题外话:
例如,假设希望将一个列表的前10个元素添加到另一个容器中,可以建立一个子列表用于选择前10个元素:

relocated.addAll(staff.subList(0,10));

这个子范围也可以成为更改操作的对象
staff.subList(0,10).clear()

0 0
原创粉丝点击