用JS的forEach函数循环嵌套比较。
需求:计算出集合1存在且在集合2不存在的元素列表。
代码实现如下:
public class CollectionUtils {
/**
* 计算集合的单差集,即只返回【集合1】中有,但是【集合2】中没有的元素,例如:
*
* <pre>
* subtractToList([1,2,3,4],[2,3,4,5]) -》 [1]
* </pre>
*
* @param coll1 集合1
* @param coll2 集合2
* @param <T> 元素类型
* @return 单差集
*/
public static <T> List<T> subtractToList(Collection<T> coll1, Collection<T> coll2) {
if (isEmpty(coll1)) {
return Collections.emptyList();
}
if (isEmpty(coll2)) {
return new LinkedList<>(coll1);
}
//将被交数用链表储存,防止因为频繁扩容影响性能
final List<T> result = new LinkedList<>();
Set<T> set = new HashSet<>(coll2);
for (T t : coll1) {
if (!set.contains(t)) {
result.add(t);
}
}
return result;
}
/**
* 集合是否为空
*
* @param collection 集合
* @return 是否为空
*/
public static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
}
测试代码如下:
public class Item {
private String name;
public Item(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Item item = (Item) o;
return Objects.equals(name, item.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public String toString() {
return "Item{" +
"name='" + name + '\'' +
'}';
}
}
public class Test {
public static void main(String[] args) {
List<Item> a1 = Arrays.asList(new Item("Bill"), new Item("George不相同"), new Item("Thomas"));
List<Item> a2 = Arrays.asList(new Item("Bill"), new Item("Thomas"));
// a1 存在 a2 不存在的集合
List<Item> subtractList = CollectionUtils.subtractToList(a1, a2);
System.out.println(subtractList);
}
}
打印结果如下:
[Item{name='George不相同'}]