Java中取两个集合的并集、交加和差集

 java如何求两个集合的交集和并集呢??

其实java的API中已经封装了方法。今天写个简单的例子测试一下:(例子中以java.util.ArrayList为例)


package org.suk;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Description: 
* @version V1.0 by 石冬冬-Heil Hitler on 2017/4/7 13:08 */ public class Test { /** * Description: 并集
* @version V1.0 2017/4/7 13:09 by 石冬冬-Heil Hilter([email protected]) * @return */ public static void union(){ List list1 = new ArrayList(){{ add("A"); add("B"); add("C"); }}; List list2 = new ArrayList(){{ add("C"); add("D"); add("B"); }}; //求出并集 list1.addAll(list2); System.out.println(list1); } /** * Description: 交集
* @version V1.0 2017/4/7 13:09 by 石冬冬-Heil Hilter([email protected]) * @return */ public static void intersection(){ List list1 = new ArrayList(){{ add("A"); add("B"); add("C"); }}; List list2 = new ArrayList(){{ add("C"); add("D"); add("B"); }}; //求出交集 list1.retainAll(list2); System.out.println(list1); } /** * Description: 差集
* @version V1.0 2017/4/7 13:09 by 石冬冬-Heil Hilter([email protected]) * @return */ public static void diff(){ List list1 = new ArrayList(){{ add("A"); add("B"); add("C"); }}; List list2 = new ArrayList(){{ add("C"); add("D"); add("B"); }}; //求出差集 list1.removeAll(list2); System.out.println(list1); } /** * Description: 对象集合的交集
* @version V1.0 2017/4/7 13:21 by 石冬冬-Heil Hilter([email protected]) * @param null * @return */ public static void test(){ List list1 = new ArrayList(){{ add(new Student("Linda",20)); add(new Student("Bruce",20)); add(new Student("Linda",21)); }}; List list2 = new ArrayList(){{ add(new Student("Linda",21)); add(new Student("Bruce",22)); add(new Student("Jack",21)); }}; //求出交集 list1.retainAll(list2); System.out.println(list1); } public static void main(String[] args) { union(); intersection(); diff(); test(); } /** * Description: 内部学生类
* @version V1.0 2017/4/7 13:20 by 石冬冬-Heil Hilter([email protected]) * @param null * @return */ public static class Student{ private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int hashCode() { return (this.getName() + String.valueOf(this.getAge())).hashCode(); } @Override public boolean equals(Object obj) { if(null == obj) return false; if(obj instanceof Student){ Student other = (Student)obj; return this.getName().equals(other.getName()) && this.getAge() == other.getAge(); } return false; } @Override public String toString() { return MessageFormat.format("[name:{0},age:{1}]",this.getName(),this.getAge()); } } }


输出的结果依次是:


[A, B, C, C, D, B]
[B, C]
[A]
[[name:Linda,age:21]]



你可能感兴趣的:(JavaWeb)