java list集合运算

时间:2022-01-28 12:59:12

list集合运算

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List; public class ListDemo { public static void main(String[] args) throws IOException, ClassNotFoundException {
// TODO Auto-generated method stub
List <String> listA = new ArrayList <String>();
listA.add("aa");
listA.add("bb");
listA.add("cc"); List <String> listB = new ArrayList <String>();
listB.add("cc");
listB.add("dd");
listB.add("ff"); List <String> listC = new ArrayList <String>(); listC = deepCopy(listA); //求并集
listA.addAll(listB);
System.out.println("--并集--" +listA);
//--并集--[aa, bb, cc, cc, dd, ff] //交集
listA = deepCopy(listC);
listA.retainAll(listB);
System.out.println("--交集--" +listA);
//--交集--[cc] //差集
listA = deepCopy(listC);
listA.removeAll(listB);
System.out.println("--差集--" +listA);
//--差集--[aa, bb] //无重复并集
listA = deepCopy(listC);
listA.removeAll(listB);
listA.addAll(listB);
System.out.println("--无重复并集--" +listA);
//--无重复并集--[aa, bb, cc, dd, ff] } public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {
/**
* 深拷贝
*/
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src); ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
@SuppressWarnings("unchecked")
List<T> dest = (List<T>) in.readObject();
return dest;
}
}