public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
list1.add("1");
list1.add("2");
list1.add("3");
list2.add("2");
list2.add("3");
list2.add("4");
System.out.println("list1集合:" + list1);
System.out.println("list2集合:" + list2);
list1.retainAll(list2);
System.out.println("两集合交集:" + list1);
}
输出结果
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
list1.add("1");
list1.add("2");
list1.add("3");
list2.add("2");
list2.add("3");
list2.add("4");
System.out.println("list1集合:" + list1);
System.out.println("list2集合:" + list2);
System.out.println("两集合差值:" + getDiffrent(list1,list2));
}
//两集合差值
public static List<String> getDiffrent(List<String> list1, List<String> list2)
{
Map<String,Integer> map = new HashMap<String,Integer>(list1.size()+list2.size());
List<String> diff = new ArrayList<String>();
List<String> maxList = list1;
List<String> minList = list2;
if(list2.size()>list1.size())
{
maxList = list2;
minList = list1;
}
for (String string : maxList)
{
map.put(string, 1);
}
for (String string : minList)
{
Integer cc = map.get(string);
if(cc!=null)
{
map.put(string, ++cc);
continue;
}
map.put(string, 1);
}
for(Map.Entry<String, Integer> entry:map.entrySet())
{
if(entry.getValue()==1)
{
diff.add(entry.getKey());
}
}
return diff;
}
输出结果
//并集
System.out.println("list1集合:" + list1);
System.out.println("list2集合:" + list2);
list1.addAll(list2);
System.out.println("两集合并集:" +list1);
输出结果
//无重复并集
System.out.println("list1集合:" + list1);
System.out.println("list2集合:" + list2);
list1.removeAll(list2);
list1.addAll(list2);
System.out.println("两集合无重复并集:" +list1);
输出结果