imtoken钱包中国官方网站|collectionutils
imtoken钱包中国官方网站|collectionutils
java代码之美(12)---CollectionUtils工具类 - 雨点的名字 - 博客园
java代码之美(12)---CollectionUtils工具类 - 雨点的名字 - 博客园
会员
周边
新闻
博问
AI培训
云市场
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式 ...
退出登录
注册
登录
雨点的名字
公众号: 后端元宇宙
首页
新随笔
管理
java代码之美(12)---CollectionUtils工具类
CollectionUtils工具类
这篇讲的CollectionUtils工具类是在apache下的, 而不是springframework下的CollectionUtils。
个人觉得CollectionUtils在真实项目中,可以使你的代码更加简洁和安全。
所以需要倒入相关jar包,目前从maven找到最新jar包如下:
一、API常用方法
/**
* 1、除非元素为null,否则向集合添加元素
*/
CollectionUtils.addIgnoreNull(personList,null);
/**
* 2、将两个已排序的集合a和b合并为一个已排序的列表,以便保留元素的自然顺序
*/
CollectionUtils.collate(Iterable extends O> a, Iterable extends O> b)
/**
* 3、将两个已排序的集合a和b合并到一个已排序的列表中,以便保留根据Comparator c的元素顺序。
*/
CollectionUtils.collate(Iterable extends O> a, Iterable extends O> b, Comparator super O> c)
/**
* 4、返回该个集合中是否含有至少有一个元素
*/
CollectionUtils.containsAny(Collection> coll1, T... coll2)
/**
* 5、如果参数是null,则返回不可变的空集合,否则返回参数本身。(很实用 ,最终返回List EMPTY_LIST = new EmptyList<>())
*/
CollectionUtils.emptyIfNull(Collection
/**
* 6、空安全检查指定的集合是否为空
*/
CollectionUtils.isEmpty(Collection> coll)
/**
* 7、 空安全检查指定的集合是否为空。
*/
CollectionUtils.isNotEmpty(Collection> coll)
/**
* 8、反转给定数组的顺序。
*/
CollectionUtils.reverseArray(Object[] array);
/**
* 9、差集
*/
CollectionUtils.subtract(Iterable extends O> a, Iterable extends O> b)
/**
* 10、并集
*/
CollectionUtils.union(Iterable extends O> a, Iterable extends O> b)
/**
* 11、交集
*/
CollectionUtils.intersection(Collection a, Collection b)
/**
*12、 交集的补集(析取)
*/
CollectionUtils.disjunction(Collection a, Collection b)
二、非对象集合交、并、差处理
对于集合取交集、并集的处理其实有很多种方式,这里就介绍3种
第一种 是CollectionUtils工具类
第二种 是List自带方法
第三种 是JDK1.8 stream 新特性
1、CollectionUtils工具类
下面对于基本数据(包扩String)类型中的集合进行demo示例。
public static void main(String[] args) {
String[] arrayA = new String[] { "1", "2", "3", "4"};
String[] arrayB = new String[] { "3", "4", "5", "6" };
List
List
//1、并集 union
System.out.println(CollectionUtils.union(listA, listB));
//输出: [1, 2, 3, 4, 5, 6]
//2、交集 intersection
System.out.println(CollectionUtils.intersection(listA, listB));
//输出:[3, 4]
//3、交集的补集(析取)disjunction
System.out.println(CollectionUtils.disjunction(listA, listB));
//输出:[1, 2, 5, 6]
//4、差集(扣除)
System.out.println(CollectionUtils.subtract(listA, listB));
//输出:[1, 2]
}
2、List自带方法
public static void main(String[] args) {
String[] arrayA = new String[] { "1", "2", "3", "4"};
String[] arrayB = new String[] { "3", "4", "5", "6" };
List
List
//1、交集
List
jiaoList.retainAll(listB);
System.out.println(jiaoList);
//输出:[3, 4]
//2、差集
List
chaList.removeAll(listB);
System.out.println(chaList);
//输出:[1, 2]
//3、并集 (先做差集再做添加所有)
List
bingList.removeAll(listB); // bingList为 [1, 2]
bingList.addAll(listB); //添加[3,4,5,6]
System.out.println(bingList);
//输出:[1, 2, 3, 4, 5, 6]
}
注意 : intersection和retainAll的差别
要注意的是它们的返回类型是不一样的,intersection返回的是一个新的List集合,而retainAll返回是Bollean类型那就说明retainAll方法是对原有集合进行处理再返回原有集合,会改变原有集合中的内容。
个人观点:1、从性能角度来考虑的话,List自带会高点,因为它不用再创建新的集合。2、需要注意的是:因为retainAll因为会改变原有集合,所以该集合需要多次使用就不适合用retainAll。
注意 : Arrays.asList将数组转集合不能进行add和remove操作。
原因:调用Arrays.asList()生产的List的add、remove方法时报异常,这是由Arrays.asList() 返回的市Arrays的内部类ArrayList, 而不是java.util.ArrayList。Arrays的内部类ArrayList和java.util.ArrayList都是继承AbstractList,remove、add等方法AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。java.util.ArrayList重新了这些方法而Arrays的内部类ArrayList没有重新,所以会抛出异常。
所以正确做法如下
String[] array = {"1","2","3","4","5"};
List
List arrList = new ArrayList(list);
arrList.add("6");
3、JDK1.8 stream 新特性
public static void main(String[] args) {
String[] arrayA = new String[] { "1", "2", "3", "4"};
String[] arrayB = new String[] { "3", "4", "5", "6" };
List
List
// 交集
List
System.out.println(intersection);
//输出:[3, 4]
// 差集 (list1 - list2)
List
System.out.println(reduceList);
//输出:[1, 2]
// 并集 (新建集合:1、是因为不影响原始集合。2、Arrays.asList不能add和remove操作。
List
List
listAll.addAll(listAll2);
System.out.println(listAll);
//输出:[1, 2, 3, 4, 3, 4, 5, 6]
// 去重并集
List
list.addAll(listB);
List
System.out.println(listAllDistinct);
//输出:[1, 2, 3, 4, 5, 6]
}
总结 : 这三种我还是最喜欢第一种方式,因为第二种还需要确定该集合是否被多次调用。第三种可读性不高。
三、对象集合交、并、差处理
因为对象的equels比较是比较两个对象的内存地址,所以除非是同一对象,否则equel返回永远是false。
但我们实际开发中 在我们的业务系统中判断对象时有时候需要的不是一种严格意义上的相等,而是一种业务上的对象相等。在这种情况下,原生的equals方法就不能满足我们的需求了,所以这个时候我们需要重写equals方法。
说明 :String为什么可以使用equels方法为什么只要字符串相等就为true,那是因为String类重写了equal和hashCode方法,比较的是值。
1、Person对象
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
/**
* 为什么重写equals方法一定要重写hashCode方法下面也会讲
*/
@Override
public int hashCode() {
String result = name + age;
return result.hashCode();
}
/**
* 重写 equals 方法 根据name和age都相同那么对象就默认相同
*/
@Override
public boolean equals(Object obj) {
Person u = (Person) obj;
return this.getName().equals(u.getName()) && (this.age.equals(u.getAge()));
}
/**
* 重写 toString 方法
*/
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2、测试
这里根据name和age都相同那么就默认相同对象。
public static void main(String[] args) {
List
Person person1 = new Person("小小",3);
Person person2 = new Person("中中",4);
personList.add(person1);
personList.add(person2);
List
Person person3 = new Person("中中",4);
Person person4 = new Person("大大",5);
person1List.add(person3);
person1List.add(person4);
/**
* 1、差集
*/
System.out.println(CollectionUtils.subtract(personList, person1List));
//输出:[Person{name='小小', age=3}]
/**
* 2、并集
*/
System.out.println(CollectionUtils.union(personList, person1List));
//输出:[Person{name='小小', age=3}, Person{name='中中', age=4}, Person{name='大大', age=5}]
/**
* 3、交集
*/
System.out.println(CollectionUtils.intersection(personList, person1List));
//输出:[Person{name='中中', age=4}]
/**
* 4、交集的补集(析取)
*/
System.out.println(CollectionUtils.disjunction(personList, person1List));
//输出:[Person{name='小小', age=3}, Person{name='大大', age=5}]
}
其它两种方式就不在测了,因为都一样。
四、为什么重写equels方法一定要重写hashCode方法
1、源码
其实上面的Person类我可以只重写equels方法而不写hashCode方法,一样能达到上面的效果。但为什么还是建议写上呢?官方的说法是:对象的equals方法被重写,那么对象的hashCode()也尽量重写。
重写equals()方法就必须重写hashCode()方法的原因,从源头Object类讲起就更好理解了。
先来看Object关于hashCode()和equals()的源码:
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
光从代码中我们可以知道,hashCode()方法是一个本地native方法,返回的是对象引用中存储的对象的内存地址。而equals方法是利用==来比较的也是对象的内存地址。从上边我们可以看出,hashCode方法和equals方法是一致的。还有最关键的一点,我们来看Object类中关于hashCode()方法的注释:
1.在 Java 应用程序执行期间,在对同一对象多次调用 hashCode 方法时,必须一致地返回相同的整数,前提是将对象进行 equals 比较时所用的信息没有被修改。
2.如果根据 equals(Object) 方法,两个对象是相等的,那么对这两个对象中的每个对象调用 hashCode 方法都必须生成相同的整数结果。
3.如果根据 equals(java.lang.Object) 方法,两个对象不相等,那么对这两个对象中的任一对象上调用 hashCode 方法不 要求一定生成不同的整数结果。
但是,程序员应该意识到,为不相等的对象生成不同整数结果可以提高哈希表的性能。
整理 : hashCode()和equals()保持一致,如果equals方法返回true,那么两个对象的hasCode()返回值必须一样。如果equals方法返回false,hashcode可以不一样,但是这样不利于哈希表的性能,一般我们也不要这样做。
假设两个对象,重写了其equals方法,其相等条件是某属性相等,就返回true。如果不重写hashcode方法,其返回的依然是两个对象的内存地址值,必然不相等。这就出现了equals方法相等,但是hashcode不相等的情况。这不符合hashcode的规则。
2、HashSet和Map集合类型
重写equals()方法就必须重写hashCode()方法主要是针对HashSet和Map集合类型,而对于List集合倒没什么影响。
原因: 在向HashSet集合中存入一个元素时,HashSet会调用该对象(存入对象)的hashCode()方法来得到该对象的hashCode()值,然后根据该hashCode值决定该对象在HashSet中存储的位置。简单的说:HashSet集合判断两个元素相等的标准是:两个对象通过equals()方法比较相等,并且两个对象的HashCode()方法返回值也相等。如果两个元素通过equals()方法比较返回true,但是它们的hashCode()方法返回值不同,HashSet会把它们存储在不同的位置,依然可以添加成功。
这就是问题所在:就是如果你只重写equals()方法,而不重写hashCode(),如果equals()为true,而它们的hashCode()方法返回值肯定不一样,因为它们都不是同一对象所以内存地址肯定不一样,所以它还是添加成功了,那么其实你写的equals()方法根本没啥软用。
3、代码示例
1、People类
重写equals方法,但并没有hashCode方法。
public class People {
private String name;
private Integer age;
public People(String name, Integer age) {
this.name = name;
this.age = age;
}
/**
* 重写 equals 方法
*/
@Override
public boolean equals(Object obj) {
People u = (People) obj;
return this.getName().equals(u.getName()) && (this.age.equals(u.getAge()));
}
/**
* 重写 toString 方法
*/
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2、实现类
public static void main(String[] args) {
HashSet
People people1 = new People("小小",3);
People people2 = new People("中中",4);
People people3 = new People("中中",4);
People people4 = new People("大大",5);
hashSet.add(people1);
hashSet.add(people2);
hashSet.add(people3);
hashSet.add(people4);
System.out.println(hashSet);
//输出:[People{name='小小', age=3}, People{name='中中', age=4}, People{name='大大', age=5}, People{name='中中', age=4}]
}
很明显,我重写了equals方法,那么people2和people3的equals应该相同,所以不能放入HashSet,但它们的hashCode()方法返回不同,所以导致同样能放入HashSet。
重点:对于Set集合必须要同时重写这两个方法,要不然Set的特性就被破坏了。
只要自己变优秀了,其他的事情才会跟着好起来(少将8)
posted on
2019-04-28 21:57
雨点的名字
阅读(40737)
评论(4)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面返回顶部
Powered by: 博客园
Copyright © 2024 雨点的名字
Powered by .NET 8.0 on Kubernetes
CollectionUtils (Apache Commons Collections 4.4 API)
CollectionUtils (Apache Commons Collections 4.4 API)
JavaScript is disabled on your browser.
Skip navigation links
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Prev Class
Next Class
Frames
No Frames
All Classes
Summary:
Nested |
Field |
Constr |
Method
Detail:
Field |
Constr |
Method
org.apache.commons.collections4
Class CollectionUtils
java.lang.Object
org.apache.commons.collections4.CollectionUtils
public class CollectionUtils
extends Object
Provides utility methods and decorators for Collection instances.
Various utility methods might put the input objects into a Set/Map/Bag. In case
the input objects override Object.equals(Object), it is mandatory that
the general contract of the Object.hashCode() method is maintained.
NOTE: From 4.0, method parameters will take Iterable objects when possible.
Since:
1.0
Field Summary
Fields
Modifier and Type
Field and Description
static Collection
EMPTY_COLLECTION
An empty unmodifiable collection.
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods
Modifier and Type
Method and Description
static
addAll(Collection
C... elements)
Adds all elements in the array to the given collection.
static
addAll(Collection
Enumeration extends C> enumeration)
Adds all elements in the enumeration to the given collection.
static
addAll(Collection
Iterable extends C> iterable)
Adds all elements in the Iterable to the given collection.
static
addAll(Collection
Iterator extends C> iterator)
Adds all elements in the iteration to the given collection.
static
addIgnoreNull(Collection
T object)
Adds an element to the collection unless the element is null.
static
cardinality(O obj,
Iterable super O> coll)
Deprecated.
since 4.1, use IterableUtils.frequency(Iterable, Object) instead.
Be aware that the order of parameters has changed.
static
collate(Iterable extends O> a,
Iterable extends O> b)
Merges two sorted Collections, a and b, into a single, sorted List
such that the natural ordering of the elements is retained.
static
collate(Iterable extends O> a,
Iterable extends O> b,
boolean includeDuplicates)
Merges two sorted Collections, a and b, into a single, sorted List
such that the natural ordering of the elements is retained.
static
collate(Iterable extends O> a,
Iterable extends O> b,
Comparator super O> c)
Merges two sorted Collections, a and b, into a single, sorted List
such that the ordering of the elements according to Comparator c is retained.
static
collate(Iterable extends O> a,
Iterable extends O> b,
Comparator super O> c,
boolean includeDuplicates)
Merges two sorted Collections, a and b, into a single, sorted List
such that the ordering of the elements according to Comparator c is retained.
static >R
collect(Iterable extends I> inputCollection,
Transformer super I,? extends O> transformer,
R outputCollection)
Transforms all elements from input collection with the given transformer
and adds them to the output collection.
static Collection
collect(Iterable inputCollection,
Transformer super I,? extends O> transformer)
Returns a new Collection containing all elements of the input collection
transformed by the given transformer.
static >R
collect(Iterator extends I> inputIterator,
Transformer super I,? extends O> transformer,
R outputCollection)
Transforms all elements from the input iterator with the given transformer
and adds them to the output collection.
static Collection
collect(Iterator inputIterator,
Transformer super I,? extends O> transformer)
Transforms all elements from the input iterator with the given transformer
and adds them to the output collection.
static boolean
containsAll(Collection> coll1,
Collection> coll2)
Returns true iff all elements of coll2 are also contained
in coll1.
static boolean
containsAny(Collection> coll1,
Collection> coll2)
Returns true iff at least one element is in both collections.
static
containsAny(Collection> coll1,
T... coll2)
Returns true iff at least one element is in both collections.
static
countMatches(Iterable
Predicate super C> predicate)
Deprecated.
since 4.1, use IterableUtils.countMatches(Iterable, Predicate) instead
static
disjunction(Iterable extends O> a,
Iterable extends O> b)
Returns a Collection containing the exclusive disjunction
(symmetric difference) of the given Iterables.
static
emptyCollection()
Returns the immutable EMPTY_COLLECTION with generic type safety.
static
emptyIfNull(Collection
Returns an immutable empty collection if the argument is null,
or the argument itself otherwise.
static
exists(Iterable
Predicate super C> predicate)
Deprecated.
since 4.1, use IterableUtils.matchesAny(Iterable, Predicate) instead
static
extractSingleton(Collection
Extract the lone element of the specified Collection.
static
filter(Iterable
Predicate super T> predicate)
Filter the collection by applying a Predicate to each element.
static
filterInverse(Iterable
Predicate super T> predicate)
Filter the collection by applying a Predicate to each element.
static
find(Iterable
Predicate super T> predicate)
Deprecated.
since 4.1, use IterableUtils.find(Iterable, Predicate) instead
static
forAllButLastDo(Iterable
C closure)
Deprecated.
since 4.1, use IterableUtils.forEachButLast(Iterable, Closure) instead
static
forAllButLastDo(Iterator
C closure)
Deprecated.
since 4.1, use IteratorUtils.forEachButLast(Iterator, Closure) instead
static
forAllDo(Iterable
C closure)
Deprecated.
since 4.1, use IterableUtils.forEach(Iterable, Closure) instead
static
forAllDo(Iterator
C closure)
Deprecated.
since 4.1, use IteratorUtils.forEach(Iterator, Closure) instead
static
get(Iterable
int index)
Deprecated.
since 4.1, use IterableUtils.get(Iterable, int) instead
static
get(Iterator
int index)
Deprecated.
since 4.1, use IteratorUtils.get(Iterator, int) instead
static
get(Map
int index)
Returns the index-th Map.Entry in the map's entrySet,
throwing IndexOutOfBoundsException if there is no such element.
static Object
get(Object object,
int index)
Returns the index-th value in object, throwing
IndexOutOfBoundsException if there is no such element or
IllegalArgumentException if object is not an
instance of one of the supported types.
static
getCardinalityMap(Iterable extends O> coll)
Returns a Map mapping each unique element in the given
Collection to an Integer representing the number
of occurrences of that element in the Collection.
static
intersection(Iterable extends O> a,
Iterable extends O> b)
Returns a Collection containing the intersection of the given
Iterables.
static boolean
isEmpty(Collection> coll)
Null-safe check if the specified collection is empty.
static boolean
isEqualCollection(Collection> a,
Collection> b)
Returns true iff the given Collections contain
exactly the same elements with exactly the same cardinalities.
static
isEqualCollection(Collection extends E> a,
Collection extends E> b,
Equator super E> equator)
Returns true iff the given Collections contain
exactly the same elements with exactly the same cardinalities.
static boolean
isFull(Collection extends Object> coll)
Returns true if no more elements can be added to the Collection.
static boolean
isNotEmpty(Collection> coll)
Null-safe check if the specified collection is not empty.
static boolean
isProperSubCollection(Collection> a,
Collection> b)
Returns true iff a is a proper sub-collection of b,
that is, iff the cardinality of e in a is less
than or equal to the cardinality of e in b,
for each element e in a, and there is at least one
element f such that the cardinality of f in b
is strictly greater than the cardinality of f in a.
static boolean
isSubCollection(Collection> a,
Collection> b)
Returns true iff a is a sub-collection of b,
that is, iff the cardinality of e in a is less than or
equal to the cardinality of e in b, for each element e
in a.
static
matchesAll(Iterable
Predicate super C> predicate)
Deprecated.
since 4.1, use IterableUtils.matchesAll(Iterable, Predicate) instead
static int
maxSize(Collection extends Object> coll)
Get the maximum number of elements that the Collection can contain.
static >
permutations(Collection
Returns a Collection of all the permutations of the input collection.
static
predicatedCollection(Collection
Predicate super C> predicate)
Returns a predicated (validating) collection backed by the given collection.
static
removeAll(Collection
Collection> remove)
Removes the elements in remove from collection.
static
removeAll(Iterable
Iterable extends E> remove,
Equator super E> equator)
Removes all elements in remove from collection.
static
retainAll(Collection
Collection> retain)
Returns a collection containing all the elements in collection
that are also in retain.
static
retainAll(Iterable
Iterable extends E> retain,
Equator super E> equator)
Returns a collection containing all the elements in
collection that are also in retain.
static void
reverseArray(Object[] array)
Reverses the order of the given array.
static
select(Iterable extends O> inputCollection,
Predicate super O> predicate)
Selects all elements from input collection which match the given
predicate into an output collection.
static
select(Iterable extends O> inputCollection,
Predicate super O> predicate,
R outputCollection)
Selects all elements from input collection which match the given
predicate and adds them to outputCollection.
static
select(Iterable extends O> inputCollection,
Predicate super O> predicate,
R outputCollection,
R rejectedCollection)
Selects all elements from inputCollection into an output and rejected collection,
based on the evaluation of the given predicate.
static
selectRejected(Iterable extends O> inputCollection,
Predicate super O> predicate)
Selects all elements from inputCollection which don't match the given
predicate into an output collection.
static
selectRejected(Iterable extends O> inputCollection,
Predicate super O> predicate,
R outputCollection)
Selects all elements from inputCollection which don't match the given
predicate and adds them to outputCollection.
static int
size(Object object)
Gets the size of the collection/iterator specified.
static boolean
sizeIsEmpty(Object object)
Checks if the specified collection/array/iterator is empty.
static
subtract(Iterable extends O> a,
Iterable extends O> b)
Returns a new Collection containing a - b.
static
subtract(Iterable extends O> a,
Iterable extends O> b,
Predicate
Returns a new Collection containing a minus a subset of
b.
static
synchronizedCollection(Collection
Deprecated.
since 4.1, use Collections.synchronizedCollection(Collection) instead
static
transform(Collection
Transformer super C,? extends C> transformer)
Transform the collection by applying a Transformer to each element.
static
transformingCollection(Collection
Transformer super E,? extends E> transformer)
Returns a transformed bag backed by the given collection.
static
union(Iterable extends O> a,
Iterable extends O> b)
Returns a Collection containing the union of the given
Iterables.
static
unmodifiableCollection(Collection extends C> collection)
Deprecated.
since 4.1, use Collections.unmodifiableCollection(Collection) instead
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Field Detail
EMPTY_COLLECTION
public static final Collection EMPTY_COLLECTION
An empty unmodifiable collection.
The JDK provides empty Set and List implementations which could be used for
this purpose. However they could be cast to Set or List which might be
undesirable. This implementation only implements Collection.
Method Detail
emptyCollection
public static
Returns the immutable EMPTY_COLLECTION with generic type safety.
Type Parameters:
T - the element type
Returns:
immutable empty collection
Since:
4.0
See Also:
EMPTY_COLLECTION
emptyIfNull
public static
Returns an immutable empty collection if the argument is null,
or the argument itself otherwise.
Type Parameters:
T - the element type
Parameters:
collection - the collection, possibly null
Returns:
an empty collection if the argument is null
union
public static
Iterable extends O> b)
Returns a Collection containing the union of the given
Iterables.
The cardinality of each element in the returned Collection will
be equal to the maximum of the cardinality of that element in the two
given Iterables.
Type Parameters:
O - the generic type that is able to represent the types contained
in both input collections.
Parameters:
a - the first collection, must not be null
b - the second collection, must not be null
Returns:
the union of the two collections
See Also:
Collection.addAll(java.util.Collection extends E>)
intersection
public static
Iterable extends O> b)
Returns a Collection containing the intersection of the given
Iterables.
The cardinality of each element in the returned Collection will
be equal to the minimum of the cardinality of that element in the two
given Iterables.
Type Parameters:
O - the generic type that is able to represent the types contained
in both input collections.
Parameters:
a - the first collection, must not be null
b - the second collection, must not be null
Returns:
the intersection of the two collections
See Also:
Collection.retainAll(java.util.Collection>),
containsAny(java.util.Collection>, T...)
disjunction
public static
Iterable extends O> b)
Returns a Collection containing the exclusive disjunction
(symmetric difference) of the given Iterables.
The cardinality of each element e in the returned
Collection will be equal to
max(cardinality(e,a),cardinality(e,b)) - min(cardinality(e,a),
cardinality(e,b)).
This is equivalent to
{@link #subtract subtract}({@link #union union(a,b)},{@link #intersection intersection(a,b)})
or
{@link #union union}({@link #subtract subtract(a,b)},{@link #subtract subtract(b,a)}).
Type Parameters:
O - the generic type that is able to represent the types contained
in both input collections.
Parameters:
a - the first collection, must not be null
b - the second collection, must not be null
Returns:
the symmetric difference of the two collections
subtract
public static
Iterable extends O> b)
Returns a new Collection containing a - b.
The cardinality of each element e in the returned Collection
will be the cardinality of e in a minus the cardinality
of e in b, or zero, whichever is greater.
Type Parameters:
O - the generic type that is able to represent the types contained
in both input collections.
Parameters:
a - the collection to subtract from, must not be null
b - the collection to subtract, must not be null
Returns:
a new collection with the results
See Also:
Collection.removeAll(java.util.Collection>)
subtract
public static
Iterable extends O> b,
Predicate
Returns a new Collection containing a minus a subset of
b. Only the elements of b that satisfy the predicate
condition, p are subtracted from a.
The cardinality of each element e in the returned Collection
that satisfies the predicate condition will be the cardinality of e in a
minus the cardinality of e in b, or zero, whichever is greater.
The cardinality of each element e in the returned Collection that does not
satisfy the predicate condition will be equal to the cardinality of e in a.
Type Parameters:
O - the generic type that is able to represent the types contained
in both input collections.
Parameters:
a - the collection to subtract from, must not be null
b - the collection to subtract, must not be null
p - the condition used to determine which elements of b are
subtracted.
Returns:
a new collection with the results
Since:
4.0
See Also:
Collection.removeAll(java.util.Collection>)
containsAll
public static boolean containsAll(Collection> coll1,
Collection> coll2)
Returns true iff all elements of coll2 are also contained
in coll1. The cardinality of values in coll2 is not taken into account,
which is the same behavior as Collection.containsAll(Collection).
In other words, this method returns true iff the
intersection(java.lang.Iterable extends O>, java.lang.Iterable extends O>) of coll1 and coll2 has the same cardinality as
the set of unique values from coll2. In case coll2 is empty, true
will be returned.
This method is intended as a replacement for Collection.containsAll(Collection)
with a guaranteed runtime complexity of O(n + m). Depending on the type of
Collection provided, this method will be much faster than calling
Collection.containsAll(Collection) instead, though this will come at the
cost of an additional space complexity O(n).
Parameters:
coll1 - the first collection, must not be null
coll2 - the second collection, must not be null
Returns:
true iff the intersection of the collections has the same cardinality
as the set of unique elements from the second collection
Since:
4.0
containsAny
public static
T... coll2)
Returns true iff at least one element is in both collections.
In other words, this method returns true iff the
intersection(java.lang.Iterable extends O>, java.lang.Iterable extends O>) of coll1 and coll2 is not empty.
Type Parameters:
T - the type of object to lookup in coll1.
Parameters:
coll1 - the first collection, must not be null
coll2 - the second collection, must not be null
Returns:
true iff the intersection of the collections is non-empty
Since:
4.2
See Also:
intersection(java.lang.Iterable extends O>, java.lang.Iterable extends O>)
containsAny
public static boolean containsAny(Collection> coll1,
Collection> coll2)
Returns true iff at least one element is in both collections.
In other words, this method returns true iff the
intersection(java.lang.Iterable extends O>, java.lang.Iterable extends O>) of coll1 and coll2 is not empty.
Parameters:
coll1 - the first collection, must not be null
coll2 - the second collection, must not be null
Returns:
true iff the intersection of the collections is non-empty
Since:
2.1
See Also:
intersection(java.lang.Iterable extends O>, java.lang.Iterable extends O>)
getCardinalityMap
public static
Returns a Map mapping each unique element in the given
Collection to an Integer representing the number
of occurrences of that element in the Collection.
Only those elements present in the collection will appear as
keys in the map.
Type Parameters:
O - the type of object in the returned Map. This is a super type of .
Parameters:
coll - the collection to get the cardinality map for, must not be null
Returns:
the populated cardinality map
isSubCollection
public static boolean isSubCollection(Collection> a,
Collection> b)
Returns true iff a is a sub-collection of b,
that is, iff the cardinality of e in a is less than or
equal to the cardinality of e in b, for each element e
in a.
Parameters:
a - the first (sub?) collection, must not be null
b - the second (super?) collection, must not be null
Returns:
true iff a is a sub-collection of b
See Also:
isProperSubCollection(java.util.Collection>, java.util.Collection>),
Collection.containsAll(java.util.Collection>)
isProperSubCollection
public static boolean isProperSubCollection(Collection> a,
Collection> b)
Returns true iff a is a proper sub-collection of b,
that is, iff the cardinality of e in a is less
than or equal to the cardinality of e in b,
for each element e in a, and there is at least one
element f such that the cardinality of f in b
is strictly greater than the cardinality of f in a.
The implementation assumes
a.size() and b.size() represent the
total cardinality of a and b, resp.
a.size() < Integer.MAXVALUE
Parameters:
a - the first (sub?) collection, must not be null
b - the second (super?) collection, must not be null
Returns:
true iff a is a proper sub-collection of b
See Also:
isSubCollection(java.util.Collection>, java.util.Collection>),
Collection.containsAll(java.util.Collection>)
isEqualCollection
public static boolean isEqualCollection(Collection> a,
Collection> b)
Returns true iff the given Collections contain
exactly the same elements with exactly the same cardinalities.
That is, iff the cardinality of e in a is
equal to the cardinality of e in b,
for each element e in a or b.
Parameters:
a - the first collection, must not be null
b - the second collection, must not be null
Returns:
true iff the collections contain the same elements with the same cardinalities.
isEqualCollection
public static
Collection extends E> b,
Equator super E> equator)
Returns true iff the given Collections contain
exactly the same elements with exactly the same cardinalities.
That is, iff the cardinality of e in a is
equal to the cardinality of e in b,
for each element e in a or b.
Note: from version 4.1 onwards this method requires the input
collections and equator to be of compatible type (using bounded wildcards).
Providing incompatible arguments (e.g. by casting to their rawtypes)
will result in a ClassCastException thrown at runtime.
Type Parameters:
E - the element type
Parameters:
a - the first collection, must not be null
b - the second collection, must not be null
equator - the Equator used for testing equality
Returns:
true iff the collections contain the same elements with the same cardinalities.
Throws:
NullPointerException - if the equator is null
Since:
4.0
cardinality
@Deprecated
public static
Iterable super O> coll)
Deprecated. since 4.1, use IterableUtils.frequency(Iterable, Object) instead.
Be aware that the order of parameters has changed.
Returns the number of occurrences of obj in coll.
Type Parameters:
O - the type of object that the Iterable may contain.
Parameters:
obj - the object to find the cardinality of
coll - the Iterable to search
Returns:
the number of occurrences of obj in coll
Throws:
NullPointerException - if coll is null
find
@Deprecated
public static
Predicate super T> predicate)
Deprecated. since 4.1, use IterableUtils.find(Iterable, Predicate) instead
Finds the first element in the given collection which matches the given predicate.
If the input collection or predicate is null, or no element of the collection
matches the predicate, null is returned.
Type Parameters:
T - the type of object the Iterable contains
Parameters:
collection - the collection to search, may be null
predicate - the predicate to use, may be null
Returns:
the first element of the collection which matches the predicate or null if none could be found
forAllDo
@Deprecated
public static
C closure)
Deprecated. since 4.1, use IterableUtils.forEach(Iterable, Closure) instead
Executes the given closure on each element in the collection.
If the input collection or closure is null, there is no change made.
Type Parameters:
T - the type of object the Iterable contains
C - the closure type
Parameters:
collection - the collection to get the input from, may be null
closure - the closure to perform, may be null
Returns:
closure
forAllDo
@Deprecated
public static
C closure)
Deprecated. since 4.1, use IteratorUtils.forEach(Iterator, Closure) instead
Executes the given closure on each element in the collection.
If the input collection or closure is null, there is no change made.
Type Parameters:
T - the type of object the Iterator contains
C - the closure type
Parameters:
iterator - the iterator to get the input from, may be null
closure - the closure to perform, may be null
Returns:
closure
Since:
4.0
forAllButLastDo
@Deprecated
public static
C closure)
Deprecated. since 4.1, use IterableUtils.forEachButLast(Iterable, Closure) instead
Executes the given closure on each but the last element in the collection.
If the input collection or closure is null, there is no change made.
Type Parameters:
T - the type of object the Iterable contains
C - the closure type
Parameters:
collection - the collection to get the input from, may be null
closure - the closure to perform, may be null
Returns:
the last element in the collection, or null if either collection or closure is null
Since:
4.0
forAllButLastDo
@Deprecated
public static
C closure)
Deprecated. since 4.1, use IteratorUtils.forEachButLast(Iterator, Closure) instead
Executes the given closure on each but the last element in the collection.
If the input collection or closure is null, there is no change made.
Type Parameters:
T - the type of object the Collection contains
C - the closure type
Parameters:
iterator - the iterator to get the input from, may be null
closure - the closure to perform, may be null
Returns:
the last element in the collection, or null if either iterator or closure is null
Since:
4.0
filter
public static
Predicate super T> predicate)
Filter the collection by applying a Predicate to each element. If the
predicate returns false, remove the element.
If the input collection or predicate is null, there is no change made.
Type Parameters:
T - the type of object the Iterable contains
Parameters:
collection - the collection to get the input from, may be null
predicate - the predicate to use as a filter, may be null
Returns:
true if the collection is modified by this call, false otherwise.
filterInverse
public static
Predicate super T> predicate)
Filter the collection by applying a Predicate to each element. If the
predicate returns true, remove the element.
This is equivalent to filter(collection, PredicateUtils.notPredicate(predicate))
if predicate is != null.
If the input collection or predicate is null, there is no change made.
Type Parameters:
T - the type of object the Iterable contains
Parameters:
collection - the collection to get the input from, may be null
predicate - the predicate to use as a filter, may be null
Returns:
true if the collection is modified by this call, false otherwise.
transform
public static
Transformer super C,? extends C> transformer)
Transform the collection by applying a Transformer to each element.
If the input collection or transformer is null, there is no change made.
This routine is best for Lists, for which set() is used to do the
transformations "in place." For other Collections, clear() and addAll()
are used to replace elements.
If the input collection controls its input, such as a Set, and the
Transformer creates duplicates (or are otherwise invalid), the collection
may reduce in size due to calling this method.
Type Parameters:
C - the type of object the Collection contains
Parameters:
collection - the Collection to get the input from, may be null
transformer - the transformer to perform, may be null
countMatches
@Deprecated
public static
Predicate super C> predicate)
Deprecated. since 4.1, use IterableUtils.countMatches(Iterable, Predicate) instead
Counts the number of elements in the input collection that match the
predicate.
A null collection or predicate matches no elements.
Type Parameters:
C - the type of object the Iterable contains
Parameters:
input - the Iterable to get the input from, may be null
predicate - the predicate to use, may be null
Returns:
the number of matches for the predicate in the collection
exists
@Deprecated
public static
Predicate super C> predicate)
Deprecated. since 4.1, use IterableUtils.matchesAny(Iterable, Predicate) instead
Answers true if a predicate is true for at least one element of a
collection.
A null collection or predicate returns false.
Type Parameters:
C - the type of object the Iterable contains
Parameters:
input - the Iterable to get the input from, may be null
predicate - the predicate to use, may be null
Returns:
true if at least one element of the collection matches the predicate
matchesAll
@Deprecated
public static
Predicate super C> predicate)
Deprecated. since 4.1, use IterableUtils.matchesAll(Iterable, Predicate) instead
Answers true if a predicate is true for every element of a
collection.
A null predicate returns false.
A null or empty collection returns true.
Type Parameters:
C - the type of object the Iterable contains
Parameters:
input - the Iterable to get the input from, may be null
predicate - the predicate to use, may be null
Returns:
true if every element of the collection matches the predicate or if the
collection is empty, false otherwise
Since:
4.0
select
public static
Predicate super O> predicate)
Selects all elements from input collection which match the given
predicate into an output collection.
A null predicate matches no elements.
Type Parameters:
O - the type of object the Iterable contains
Parameters:
inputCollection - the collection to get the input from, may not be null
predicate - the predicate to use, may be null
Returns:
the elements matching the predicate (new list)
Throws:
NullPointerException - if the input collection is null
select
public static
Predicate super O> predicate,
R outputCollection)
Selects all elements from input collection which match the given
predicate and adds them to outputCollection.
If the input collection or predicate is null, there is no change to the
output collection.
Type Parameters:
O - the type of object the Iterable contains
R - the type of the output Collection
Parameters:
inputCollection - the collection to get the input from, may be null
predicate - the predicate to use, may be null
outputCollection - the collection to output into, may not be null if the inputCollection
and predicate or not null
Returns:
the outputCollection
select
public static
Predicate super O> predicate,
R outputCollection,
R rejectedCollection)
Selects all elements from inputCollection into an output and rejected collection,
based on the evaluation of the given predicate.
Elements matching the predicate are added to the outputCollection,
all other elements are added to the rejectedCollection.
If the input predicate is null, no elements are added to
outputCollection or rejectedCollection.
Note: calling the method is equivalent to the following code snippet:
select(inputCollection, predicate, outputCollection);
selectRejected(inputCollection, predicate, rejectedCollection);
Type Parameters:
O - the type of object the Iterable contains
R - the type of the output Collection
Parameters:
inputCollection - the collection to get the input from, may be null
predicate - the predicate to use, may be null
outputCollection - the collection to output selected elements into, may not be null if the
inputCollection and predicate are not null
rejectedCollection - the collection to output rejected elements into, may not be null if the
inputCollection or predicate are not null
Returns:
the outputCollection
Since:
4.1
selectRejected
public static
Predicate super O> predicate)
Selects all elements from inputCollection which don't match the given
predicate into an output collection.
If the input predicate is null, the result is an empty
list.
Type Parameters:
O - the type of object the Iterable contains
Parameters:
inputCollection - the collection to get the input from, may not be null
predicate - the predicate to use, may be null
Returns:
the elements not matching the predicate (new list)
Throws:
NullPointerException - if the input collection is null
selectRejected
public static
Predicate super O> predicate,
R outputCollection)
Selects all elements from inputCollection which don't match the given
predicate and adds them to outputCollection.
If the input predicate is null, no elements are added to
outputCollection.
Type Parameters:
O - the type of object the Iterable contains
R - the type of the output Collection
Parameters:
inputCollection - the collection to get the input from, may be null
predicate - the predicate to use, may be null
outputCollection - the collection to output into, may not be null if the inputCollection
and predicate or not null
Returns:
outputCollection
collect
public static Collection
Transformer super I,? extends O> transformer)
Returns a new Collection containing all elements of the input collection
transformed by the given transformer.
If the input collection or transformer is null, the result is an empty list.
Type Parameters:
I - the type of object in the input collection
O - the type of object in the output collection
Parameters:
inputCollection - the collection to get the input from, may not be null
transformer - the transformer to use, may be null
Returns:
the transformed result (new list)
Throws:
NullPointerException - if the input collection is null
collect
public static Collection
Transformer super I,? extends O> transformer)
Transforms all elements from the input iterator with the given transformer
and adds them to the output collection.
If the input iterator or transformer is null, the result is an empty list.
Type Parameters:
I - the type of object in the input collection
O - the type of object in the output collection
Parameters:
inputIterator - the iterator to get the input from, may be null
transformer - the transformer to use, may be null
Returns:
the transformed result (new list)
collect
public static > R collect(Iterable extends I> inputCollection,
Transformer super I,? extends O> transformer,
R outputCollection)
Transforms all elements from input collection with the given transformer
and adds them to the output collection.
If the input collection or transformer is null, there is no change to the
output collection.
Type Parameters:
I - the type of object in the input collection
O - the type of object in the output collection
R - the type of the output collection
Parameters:
inputCollection - the collection to get the input from, may be null
transformer - the transformer to use, may be null
outputCollection - the collection to output into, may not be null if inputCollection
and transformer are not null
Returns:
the output collection with the transformed input added
Throws:
NullPointerException - if the outputCollection is null and both, inputCollection and
transformer are not null
collect
public static > R collect(Iterator extends I> inputIterator,
Transformer super I,? extends O> transformer,
R outputCollection)
Transforms all elements from the input iterator with the given transformer
and adds them to the output collection.
If the input iterator or transformer is null, there is no change to the
output collection.
Type Parameters:
I - the type of object in the input collection
O - the type of object in the output collection
R - the type of the output collection
Parameters:
inputIterator - the iterator to get the input from, may be null
transformer - the transformer to use, may be null
outputCollection - the collection to output into, may not be null if inputIterator
and transformer are not null
Returns:
the outputCollection with the transformed input added
Throws:
NullPointerException - if the output collection is null and both, inputIterator and
transformer are not null
addIgnoreNull
public static
T object)
Adds an element to the collection unless the element is null.
Type Parameters:
T - the type of object the Collection contains
Parameters:
collection - the collection to add to, must not be null
object - the object to add, if null it will not be added
Returns:
true if the collection changed
Throws:
NullPointerException - if the collection is null
Since:
3.2
addAll
public static
Iterable extends C> iterable)
Adds all elements in the Iterable to the given collection. If the
Iterable is a Collection then it is cast and will be
added using Collection.addAll(Collection) instead of iterating.
Type Parameters:
C - the type of object the Collection contains
Parameters:
collection - the collection to add to, must not be null
iterable - the iterable of elements to add, must not be null
Returns:
a boolean indicating whether the collection has changed or not.
Throws:
NullPointerException - if the collection or iterator is null
addAll
public static
Iterator extends C> iterator)
Adds all elements in the iteration to the given collection.
Type Parameters:
C - the type of object the Collection contains
Parameters:
collection - the collection to add to, must not be null
iterator - the iterator of elements to add, must not be null
Returns:
a boolean indicating whether the collection has changed or not.
Throws:
NullPointerException - if the collection or iterator is null
addAll
public static
Enumeration extends C> enumeration)
Adds all elements in the enumeration to the given collection.
Type Parameters:
C - the type of object the Collection contains
Parameters:
collection - the collection to add to, must not be null
enumeration - the enumeration of elements to add, must not be null
Returns:
true if the collections was changed, false otherwise
Throws:
NullPointerException - if the collection or enumeration is null
addAll
public static
C... elements)
Adds all elements in the array to the given collection.
Type Parameters:
C - the type of object the Collection contains
Parameters:
collection - the collection to add to, must not be null
elements - the array of elements to add, must not be null
Returns:
true if the collection was changed, false otherwise
Throws:
NullPointerException - if the collection or array is null
get
@Deprecated
public static
int index)
Deprecated. since 4.1, use IteratorUtils.get(Iterator, int) instead
Returns the index-th value in Iterator, throwing
IndexOutOfBoundsException if there is no such element.
The Iterator is advanced to index (or to the end, if
index exceeds the number of entries) as a side effect of this method.
Type Parameters:
T - the type of object in the Iterator
Parameters:
iterator - the iterator to get a value from
index - the index to get
Returns:
the object at the specified index
Throws:
IndexOutOfBoundsException - if the index is invalid
IllegalArgumentException - if the object type is invalid
get
@Deprecated
public static
int index)
Deprecated. since 4.1, use IterableUtils.get(Iterable, int) instead
Returns the index-th value in the iterable's Iterator, throwing
IndexOutOfBoundsException if there is no such element.
If the Iterable is a List, then it will use List.get(int).
Type Parameters:
T - the type of object in the Iterable.
Parameters:
iterable - the Iterable to get a value from
index - the index to get
Returns:
the object at the specified index
Throws:
IndexOutOfBoundsException - if the index is invalid
get
public static Object get(Object object,
int index)
Returns the index-th value in object, throwing
IndexOutOfBoundsException if there is no such element or
IllegalArgumentException if object is not an
instance of one of the supported types.
The supported types, and associated semantics are:
Map -- the value returned is the Map.Entry in position
index in the map's entrySet iterator,
if there is such an entry.
List -- this method is equivalent to the list's get method.
Array -- the index-th array entry is returned,
if there is such an entry; otherwise an IndexOutOfBoundsException
is thrown.
Collection -- the value returned is the index-th object
returned by the collection's default iterator, if there is such an element.
Iterator or Enumeration -- the value returned is the
index-th object in the Iterator/Enumeration, if there
is such an element. The Iterator/Enumeration is advanced to
index (or to the end, if index exceeds the
number of entries) as a side effect of this method.
Parameters:
object - the object to get a value from
index - the index to get
Returns:
the object at the specified index
Throws:
IndexOutOfBoundsException - if the index is invalid
IllegalArgumentException - if the object type is invalid
get
public static
int index)
Returns the index-th Map.Entry in the map's entrySet,
throwing IndexOutOfBoundsException if there is no such element.
Type Parameters:
K - the key type in the Map
V - the key type in the Map
Parameters:
map - the object to get a value from
index - the index to get
Returns:
the object at the specified index
Throws:
IndexOutOfBoundsException - if the index is invalid
size
public static int size(Object object)
Gets the size of the collection/iterator specified.
This method can handles objects as follows
Collection - the collection size
Map - the map size
Array - the array size
Iterator - the number of elements remaining in the iterator
Enumeration - the number of elements remaining in the enumeration
Parameters:
object - the object to get the size of, may be null
Returns:
the size of the specified collection or 0 if the object was null
Throws:
IllegalArgumentException - thrown if object is not recognized
Since:
3.1
sizeIsEmpty
public static boolean sizeIsEmpty(Object object)
Checks if the specified collection/array/iterator is empty.
This method can handles objects as follows
Collection - via collection isEmpty
Map - via map isEmpty
Array - using array size
Iterator - via hasNext
Enumeration - via hasMoreElements
Note: This method is named to avoid clashing with
isEmpty(Collection).
Parameters:
object - the object to get the size of, may be null
Returns:
true if empty or null
Throws:
IllegalArgumentException - thrown if object is not recognized
Since:
3.2
isEmpty
public static boolean isEmpty(Collection> coll)
Null-safe check if the specified collection is empty.
Null returns true.
Parameters:
coll - the collection to check, may be null
Returns:
true if empty or null
Since:
3.2
isNotEmpty
public static boolean isNotEmpty(Collection> coll)
Null-safe check if the specified collection is not empty.
Null returns false.
Parameters:
coll - the collection to check, may be null
Returns:
true if non-null and non-empty
Since:
3.2
reverseArray
public static void reverseArray(Object[] array)
Reverses the order of the given array.
Parameters:
array - the array to reverse
isFull
public static boolean isFull(Collection extends Object> coll)
Returns true if no more elements can be added to the Collection.
This method uses the BoundedCollection interface to determine the
full status. If the collection does not implement this interface then
false is returned.
The collection does not have to implement this interface directly.
If the collection has been decorated using the decorators subpackage
then these will be removed to access the BoundedCollection.
Parameters:
coll - the collection to check
Returns:
true if the BoundedCollection is full
Throws:
NullPointerException - if the collection is null
maxSize
public static int maxSize(Collection extends Object> coll)
Get the maximum number of elements that the Collection can contain.
This method uses the BoundedCollection interface to determine the
maximum size. If the collection does not implement this interface then
-1 is returned.
The collection does not have to implement this interface directly.
If the collection has been decorated using the decorators subpackage
then these will be removed to access the BoundedCollection.
Parameters:
coll - the collection to check
Returns:
the maximum size of the BoundedCollection, -1 if no maximum size
Throws:
NullPointerException - if the collection is null
collate
public static
Iterable extends O> b)
Merges two sorted Collections, a and b, into a single, sorted List
such that the natural ordering of the elements is retained.
Uses the standard O(n) merge algorithm for combining two sorted lists.
Type Parameters:
O - the element type
Parameters:
a - the first collection, must not be null
b - the second collection, must not be null
Returns:
a new sorted List, containing the elements of Collection a and b
Throws:
NullPointerException - if either collection is null
Since:
4.0
collate
public static
Iterable extends O> b,
boolean includeDuplicates)
Merges two sorted Collections, a and b, into a single, sorted List
such that the natural ordering of the elements is retained.
Uses the standard O(n) merge algorithm for combining two sorted lists.
Type Parameters:
O - the element type
Parameters:
a - the first collection, must not be null
b - the second collection, must not be null
includeDuplicates - if true duplicate elements will be retained, otherwise
they will be removed in the output collection
Returns:
a new sorted List, containing the elements of Collection a and b
Throws:
NullPointerException - if either collection is null
Since:
4.0
collate
public static
Iterable extends O> b,
Comparator super O> c)
Merges two sorted Collections, a and b, into a single, sorted List
such that the ordering of the elements according to Comparator c is retained.
Uses the standard O(n) merge algorithm for combining two sorted lists.
Type Parameters:
O - the element type
Parameters:
a - the first collection, must not be null
b - the second collection, must not be null
c - the comparator to use for the merge.
Returns:
a new sorted List, containing the elements of Collection a and b
Throws:
NullPointerException - if either collection or the comparator is null
Since:
4.0
collate
public static
Iterable extends O> b,
Comparator super O> c,
boolean includeDuplicates)
Merges two sorted Collections, a and b, into a single, sorted List
such that the ordering of the elements according to Comparator c is retained.
Uses the standard O(n) merge algorithm for combining two sorted lists.
Type Parameters:
O - the element type
Parameters:
a - the first collection, must not be null
b - the second collection, must not be null
c - the comparator to use for the merge.
includeDuplicates - if true duplicate elements will be retained, otherwise
they will be removed in the output collection
Returns:
a new sorted List, containing the elements of Collection a and b
Throws:
NullPointerException - if either collection or the comparator is null
Since:
4.0
permutations
public static > permutations(Collection
Returns a Collection of all the permutations of the input collection.
NOTE: the number of permutations of a given collection is equal to n!, where
n is the size of the collection. Thus, the resulting collection will become
very large for collections > 10 (e.g. 10! = 3628800, 15! = 1307674368000).
For larger collections it is advised to use a PermutationIterator to
iterate over all permutations.
Type Parameters:
E - the element type
Parameters:
collection - the collection to create permutations for, may not be null
Returns:
an unordered collection of all permutations of the input collection
Throws:
NullPointerException - if collection is null
Since:
4.0
See Also:
PermutationIterator
retainAll
public static
Collection> retain)
Returns a collection containing all the elements in collection
that are also in retain. The cardinality of an element e
in the returned collection is the same as the cardinality of e
in collection unless retain does not contain e, in which
case the cardinality is zero. This method is useful if you do not wish to modify
the collection c and thus cannot call c.retainAll(retain);.
This implementation iterates over collection, checking each element in
turn to see if it's contained in retain. If it's contained, it's added
to the returned list. As a consequence, it is advised to use a collection type for
retain that provides a fast (e.g. O(1)) implementation of
Collection.contains(Object).
Type Parameters:
C - the type of object the Collection contains
Parameters:
collection - the collection whose contents are the target of the #retailAll operation
retain - the collection containing the elements to be retained in the returned collection
Returns:
a Collection containing all the elements of collection
that occur at least once in retain.
Throws:
NullPointerException - if either parameter is null
Since:
3.2
retainAll
public static
Iterable extends E> retain,
Equator super E> equator)
Returns a collection containing all the elements in
collection that are also in retain. The
cardinality of an element e in the returned collection is
the same as the cardinality of e in collection
unless retain does not contain e, in which case
the cardinality is zero. This method is useful if you do not wish to
modify the collection c and thus cannot call
c.retainAll(retain);.
Moreover this method uses an Equator instead of
Object.equals(Object) to determine the equality of the elements
in collection and retain. Hence this method is
useful in cases where the equals behavior of an object needs to be
modified without changing the object itself.
Type Parameters:
E - the type of object the Collection contains
Parameters:
collection - the collection whose contents are the target of the retainAll operation
retain - the collection containing the elements to be retained in the returned collection
equator - the Equator used for testing equality
Returns:
a Collection containing all the elements of collection
that occur at least once in retain according to the equator
Throws:
NullPointerException - if any of the parameters is null
Since:
4.1
removeAll
public static
Collection> remove)
Removes the elements in remove from collection. That is, this
method returns a collection containing all the elements in c
that are not in remove. The cardinality of an element e
in the returned collection is the same as the cardinality of e
in collection unless remove contains e, in which
case the cardinality is zero. This method is useful if you do not wish to modify
the collection c and thus cannot call collection.removeAll(remove);.
This implementation iterates over collection, checking each element in
turn to see if it's contained in remove. If it's not contained, it's added
to the returned list. As a consequence, it is advised to use a collection type for
remove that provides a fast (e.g. O(1)) implementation of
Collection.contains(Object).
Type Parameters:
E - the type of object the Collection contains
Parameters:
collection - the collection from which items are removed (in the returned collection)
remove - the items to be removed from the returned collection
Returns:
a Collection containing all the elements of collection except
any elements that also occur in remove.
Throws:
NullPointerException - if either parameter is null
Since:
4.0 (method existed in 3.2 but was completely broken)
removeAll
public static
Iterable extends E> remove,
Equator super E> equator)
Removes all elements in remove from collection.
That is, this method returns a collection containing all the elements in
collection that are not in remove. The
cardinality of an element e in the returned collection is
the same as the cardinality of e in collection
unless remove contains e, in which case the
cardinality is zero. This method is useful if you do not wish to modify
the collection c and thus cannot call
collection.removeAll(remove).
Moreover this method uses an Equator instead of
Object.equals(Object) to determine the equality of the elements
in collection and remove. Hence this method is
useful in cases where the equals behavior of an object needs to be
modified without changing the object itself.
Type Parameters:
E - the type of object the Collection contains
Parameters:
collection - the collection from which items are removed (in the returned collection)
remove - the items to be removed from the returned collection
equator - the Equator used for testing equality
Returns:
a Collection containing all the elements of collection
except any element that if equal according to the equator
Throws:
NullPointerException - if any of the parameters is null
Since:
4.1
synchronizedCollection
@Deprecated
public static
Deprecated. since 4.1, use Collections.synchronizedCollection(Collection) instead
Returns a synchronized collection backed by the given collection.
You must manually synchronize on the returned buffer's iterator to
avoid non-deterministic behavior:
Collection c = CollectionUtils.synchronizedCollection(myCollection);
synchronized (c) {
Iterator i = c.iterator();
while (i.hasNext()) {
process (i.next());
}
}
This method uses the implementation in the decorators subpackage.
Type Parameters:
C - the type of object the Collection contains
Parameters:
collection - the collection to synchronize, must not be null
Returns:
a synchronized collection backed by the given collection
Throws:
NullPointerException - if the collection is null
unmodifiableCollection
@Deprecated
public static
Deprecated. since 4.1, use Collections.unmodifiableCollection(Collection) instead
Returns an unmodifiable collection backed by the given collection.
This method uses the implementation in the decorators subpackage.
Type Parameters:
C - the type of object the Collection contains
Parameters:
collection - the collection to make unmodifiable, must not be null
Returns:
an unmodifiable collection backed by the given collection
Throws:
NullPointerException - if the collection is null
predicatedCollection
public static
Predicate super C> predicate)
Returns a predicated (validating) collection backed by the given collection.
Only objects that pass the test in the given predicate can be added to the collection.
Trying to add an invalid object results in an IllegalArgumentException.
It is important not to use the original collection after invoking this method,
as it is a backdoor for adding invalid objects.
Type Parameters:
C - the type of objects in the Collection.
Parameters:
collection - the collection to predicate, must not be null
predicate - the predicate for the collection, must not be null
Returns:
a predicated collection backed by the given collection
Throws:
NullPointerException - if the Collection is null
transformingCollection
public static
Transformer super E,? extends E> transformer)
Returns a transformed bag backed by the given collection.
Each object is passed through the transformer as it is added to the
Collection. It is important not to use the original collection after invoking this
method, as it is a backdoor for adding untransformed objects.
Existing entries in the specified collection will not be transformed.
If you want that behaviour, see TransformedCollection.transformedCollection(java.util.Collection
Type Parameters:
E - the type of object the Collection contains
Parameters:
collection - the collection to predicate, must not be null
transformer - the transformer for the collection, must not be null
Returns:
a transformed collection backed by the given collection
Throws:
NullPointerException - if the Collection or Transformer is null
extractSingleton
public static
Extract the lone element of the specified Collection.
Type Parameters:
E - collection type
Parameters:
collection - to read
Returns:
sole member of collection
Throws:
NullPointerException - if collection is null
IllegalArgumentException - if collection is empty or contains more than one element
Since:
4.0
Skip navigation links
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Prev Class
Next Class
Frames
No Frames
All Classes
Summary:
Nested |
Field |
Constr |
Method
Detail:
Field |
Constr |
Method
Copyright © 2001–2019 The Apache Software Foundation. All rights reserved.
Spring自带的CollectionUtils工具类_spring collectionutils-CSDN博客
>Spring自带的CollectionUtils工具类_spring collectionutils-CSDN博客
Spring自带的CollectionUtils工具类
最新推荐文章于 2023-09-01 23:45:00 发布
疯狂行者
最新推荐文章于 2023-09-01 23:45:00 发布
阅读量1.2k
收藏
1
点赞数
2
分类专栏:
javaee
文章标签:
java
开发语言
后端
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/QinTao9961220/article/details/121519258
版权
javaee
专栏收录该内容
4 篇文章
0 订阅
订阅专栏
集合判断:
判断集合是否为空:CollectionUtils.isEmpty(null): true CollectionUtils.isEmpty(new ArrayList()): true CollectionUtils.isEmpty({a,b}): false 判断集合是否不为空:CollectionUtils.isNotEmpty(null): false CollectionUtils.isNotEmpty(new ArrayList()): false CollectionUtils.isNotEmpty({a,b}): true
CollectionUtils在真实项目中,是一个非常好用的工具类,使用非常频繁。它可以使代码更加简洁和安全。刚好在工作中利用这个工具类重构代码,顺便总结下分享分享:
并集:
@Test
public void test1(){
String[] arrayA = new String[] { "A", "B", "C", "D", "E", "F" };
String[] arrayB = new String[] { "B", "D", "F", "G", "H", "K" };
List
List
//2个数组取并集
System.out.println(ArrayUtils.toString(CollectionUtils.union(listA, listB)));
//[A, B, C, D, E, F, G, H, K]
}
交集:
@Test
public void test2(){
String[] arrayA = new String[] { "A", "B", "C", "D", "E", "F" };
String[] arrayB = new String[] { "B", "D", "F", "G", "H", "K" };
List
List
//2个数组取交集
System.out.println(ArrayUtils.toString(CollectionUtils.intersection(listA, listB)));
//[B, D, F]
}
交集的补集(析取):
@Test
public void test3(){
String[] arrayA = new String[] { "A", "B", "C", "D", "E", "F" };
String[] arrayB = new String[] { "B", "D", "F", "G", "H", "K" };
List
List
//2个数组取交集 的补集
System.out.println(ArrayUtils.toString(CollectionUtils.disjunction(listA, listB)));
//[A, C, E, G, H, K]
}
差集(扣除):
@Test
public void test4(){
String[] arrayA = new String[] { "A", "B", "C", "D", "E", "F" };
String[] arrayB = new String[] { "B", "D", "F", "G", "H", "K" };
List
List
//arrayA扣除arrayB
System.out.println(ArrayUtils.toString(CollectionUtils.subtract(listA, listB)));
//[A, C, E]
}
集合是否为空:
@Test
public void test5(){
class Person{}
class Girl extends Person{}
List
List
List
//每个男孩心里都装着一个女孩
boy.add(new Girl());
//判断集合是否为空
System.out.println(CollectionUtils.isEmpty(first)); //true
System.out.println(CollectionUtils.isEmpty(second)); //true
System.out.println(CollectionUtils.isEmpty(boy)); //false
//判断集合是否不为空
System.out.println(CollectionUtils.isNotEmpty(first)); //false
System.out.println(CollectionUtils.isNotEmpty(second)); //false
System.out.println(CollectionUtils.isNotEmpty(boy)); //true
}
集合是否相等:
@Test
public void test6(){
class Person{}
class Girl extends Person{
}
List
List
first.add(1);
first.add(2);
second.add(2);
second.add(1);
Girl goldGirl = new Girl();
List
//每个男孩心里都装着一个女孩
boy1.add(new Girl());
List
//每个男孩心里都装着一个女孩
boy2.add(new Girl());
//比较两集合值
System.out.println(CollectionUtils.isEqualCollection(first,second)); //true
System.out.println(CollectionUtils.isEqualCollection(first,boy1)); //false
System.out.println(CollectionUtils.isEqualCollection(boy1,boy2)); //false
List
//每个男孩心里都装着一个女孩
boy3.add(goldGirl);
List
boy4.add(goldGirl);
System.out.println(CollectionUtils.isEqualCollection(boy3,boy4)); //true
}
不可修改的集合:
我们对c进行操作,s也同样获得了和c相同的内容,这样就可以避免其他人员修改这个s对象。有时候需要对它进行保护,避免返回结果被人修改。
@Test
public void test7(){
Collection
Collection
c.add("boy");
c.add("love");
c.add("girl");
//! s.add("have a error");
System.out.println(s);
}
Collections.unmodifiableCollection可以得到一个集合的镜像,它的返回结果是不可直接被改变,否则会提示错误
java.lang.UnsupportedOperationException at org.apache.commons.collections.collection.UnmodifiableCollection.add(UnmodifiableCollection.java:75)
优惠劵
疯狂行者
关注
关注
2
点赞
踩
1
收藏
觉得还不错?
一键收藏
打赏
知道了
0
评论
Spring自带的CollectionUtils工具类
集合判断:判断集合是否为空:CollectionUtils.isEmpty(null): true CollectionUtils.isEmpty(new ArrayList()): true CollectionUtils.isEmpty({a,b}): false判断集合是否不为空:CollectionUtils.isNotEmpty(null): false CollectionUtils.isNotEmpty(new ArrayList()): falseCol.
复制链接
扫一扫
专栏目录
简单了解Spring中常用工具类
08-29
主要介绍了简单了解Spring中常用工具类,非常全面,具有一定参考价值,需要的朋友可以了解下。
Spring Utils工具类常用方法实例
08-19
主要介绍了Spring Utils工具类常用方法实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
参与评论
您还未登录,请先
登录
后发表或查看评论
如何使用Spring工具类动态匹配url
08-25
主要介绍了如何使用Spring工具类动态匹配url,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
CollectionUtils工具类的常用方法
weixin_34332905的博客
09-10
5012
集合判断: 例1: 判断集合是否为空: CollectionUtils.isEmpty(null): true CollectionUtils.isEmpty(new ArrayList()): true CollectionUtils.isEmpty({a,b}): false 例2: 判断集合是否不为空: CollectionUtils.isNotEmpty(null):...
spring boot内置工具类
11-28
spring boot内置工具类。
对象、数组、集合
文件、资源、IO 流
反射、AOP
SpringFramework 中CollectionUtils 工具类的使用
weixin_49171365的博客
05-29
394
CollectionUtils是Spring框架中的一个工具类,提供了一系列对集合的操作方法。
Springboot内置的工具类之CollectionUtils示例讲解
gb4215287的博客
05-26
405
Springboot内置的工具类之CollectionUtils示例讲解
Java常用工具类(三):集合/数组工具类
风之子
01-30
982
1.CollectionUtils
集合判断工具
// 判断 List/Set 是否为空
boolean isEmpty(Collection> collection)
// 判断 Map 是否为空
boolean isEmpty(Map,?> map)
// 判断 List/Set 中是否包含某个对象
boolean containsInstance(Collection> collection, Object element)
// 以迭代器的方式.
collectionutils包_基于springframework的集合处理工具类CollectionUtils对常见对象查找包含转换操作...
weixin_39806288的博客
12-20
891
一、前言基于spring-core(4.1.4)的org.springframework.util.CollectionUtils集合工具类,对常见集合collect和对象、集合List、Map、数组间的转换、包含关系等之间相关操作,具体参见下面二源码说明。二、源码说明packageorg.springframework.util;@b@@b@importjava.io.Serializabl...
spring-redis工具类
04-22
Spring整合Redis工具类,导入redis依赖,并使用工具类,不必使用RedisTemplate调用redis,并且采用java更常用的方式调用方法。
Spring工具类--CollectionUtils的使用
IT利刃出鞘的博客
09-01
509
本文介绍Spring的CollectionUtils的使用。
CollectionUtils工具类的作用:操作Collection,比如:List、Set。
Spring中提供的集合工具类util CollectionUtils
weixin_34014555的博客
11-21
2635
转自:https://blog.csdn.net/fangwenzheng88/article/details/78457850
CollectionUtils类
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the ...
Spring Boot 内置工具类 CollectionUtils
qq_41525524的博客
11-02
644
Spring Boot 内置工具类 CollectionUtils
Springboot内置的工具类之CollectionUtils
凡夫编程
12-14
1711
实际业务开发中,集合的判断和操作也是经常用到的,Spring也针对集合的判断和操作封装了一些方法,但是最令我惊讶的是,我在梳理这些内容的过程中发现了一些有趣的现象,我的第一反应是不敢相信,再想一想,没错,我是对的。所以强烈建议大家可以认真看完这篇文章,这一篇绝对有价值,因为有趣的是我我竟然发现了Spring的两个bug。
CollectionUtils.isEmpty
热门推荐
developer
10-22
4万+
集合判断: 例1: 判断集合是否为空:
CollectionUtils.isEmpty(null): true
CollectionUtils.isEmpty(new ArrayList()): true
CollectionUtils.isEmpty({a,b}): false 例2: 判断集合是否不为空:
CollectionUtils.isNotEmpty(null...
Arrays.asList()使用指南
weixin_30902675的博客
08-30
134
文章来源:微信号JavaGuide-Arrays.asList()使用指南
最近使用Arrays.asList()遇到了一些坑,然后在网上看到这篇文章:http://javadevnotes.com/java-array-to-list-examples 感觉挺不错的,但是还不是很全面而且是英文的。所以,自己对于这块小知识点进行了简单的总结
简介
Arrays.asLi...
Java常用工具之Collections
zch981964的博客
05-20
1439
Collections 是 JDK 提供的一个工具类,位于 java.util 包下,提供了一系列的静态方法,方便我们对集合进行各种骚操作,算是集合框架的一个大管家。还记得我们前面讲过的 Arrays 工具类吗?可以回去温习下。Collections 的用法很简单,在 Intellij IDEA 中敲完 Collections. 之后就可以看到它提供的方法了,大致看一下方法名和参数就能知道这个方法是干嘛的。
CollectionUtils.isNotEmpty( )
m0_47073109的博客
01-06
2847
实例:
List
if (CollectionUtils.isNotEmpty(list)) {
resolutionInfoMapper.updateBatch(list);
}
CollectionUtils.isNotEmpty( ):判断list集合不能为空。
如果li
spring boot mongodb工具类
最新发布
09-07
根据提供的引用内容,可以得出spring boot mongodb工具类是基于Spring Boot2.0开发的一个网页管理工具,用于对MongoDB进行管理和操作。它使用了Mongodb提供的Java API实现,并且前端采用了layerUI框架。
在使用该工具类之前,需要在项目的pom.xml文件中添加相关的依赖:
```xml
```
同时,需要在项目的配置文件中进行配置,包括MongoDB的连接信息和认证信息,如下所示:
```yaml
spring:
data:
mongodb:
host: 127.0.0.1
port: 27017
username: test
password: mongodb
authentication-database: admin
database: test_db
```
这样就可以通过该工具类进行对MongoDB的操作了。例如,可以使用`MongodbUtils.save()`方法保存数据或使用`MongodbUtils.findAll()`方法查询所有数据。
请注意,以上配置仅供参考,需要根据实际情况进行调整。1234
“相关推荐”对你有帮助么?
非常没帮助
没帮助
一般
有帮助
非常有帮助
提交
疯狂行者
CSDN认证博客专家
CSDN认证企业博客
码龄6年
Java领域新星创作者
373
原创
2986
周排名
2244
总排名
56万+
访问
等级
9882
积分
6270
粉丝
4282
获赞
646
评论
7040
收藏
私信
关注
分类专栏
毕设项目
310篇
Java项目
46篇
Python项目
219篇
课设项目
191篇
javaee
4篇
JavaWeb技术
3篇
SpringBoot问题解决
mysql
6篇
VUE问题解决
1篇
前端模板
2篇
Redis
前端技术
5篇
Nginx
2篇
IDEA
5篇
java问题解决合总
7篇
笔记
1篇
maven
2篇
Mail-邮件
3篇
sqlserver
1篇
Linux
2篇
javase
1篇
最新评论
Java+SpringBoot+Vue+MySQL:宠物猫认养系统的全栈解决方案
CSDN-Ada助手:
不知道 MySQL入门 技能树是否可以帮到你:https://edu.csdn.net/skill/mysql?utm_source=AI_act_mysql
Java课程设计-学生成绩管理系统
疯狂行者:
你好,主页上联系我,不好意思,源码都是有偿的,有问题可以联系我
Java课程设计-学生成绩管理系统
疯狂行者:
你好,主页上联系我,不好意思,源码都是有偿的,有问题可以联系我
Java课程设计-学生成绩管理系统
9.725:
大佬能不能求个源码2944284318@qq.com
计算机毕业设计选题推荐-SpringBoot 房屋租赁系统
疯狂行者:
文章下面
您愿意向朋友推荐“博客详情页”吗?
强烈不推荐
不推荐
一般般
推荐
强烈推荐
提交
最新文章
Java+SpringBoot+Vue+MySQL:宠物猫认养系统的全栈解决方案
城乡居民医疗信息管理:Java与Spring Boot的实践
本科生交流管理平台:Java与SpringBoot的完美融合
2024
02月
46篇
01月
75篇
2023年97篇
2022年57篇
2021年56篇
2020年37篇
2019年5篇
目录
目录
分类专栏
毕设项目
310篇
Java项目
46篇
Python项目
219篇
课设项目
191篇
javaee
4篇
JavaWeb技术
3篇
SpringBoot问题解决
mysql
6篇
VUE问题解决
1篇
前端模板
2篇
Redis
前端技术
5篇
Nginx
2篇
IDEA
5篇
java问题解决合总
7篇
笔记
1篇
maven
2篇
Mail-邮件
3篇
sqlserver
1篇
Linux
2篇
javase
1篇
目录
评论
被折叠的 条评论
为什么被折叠?
到【灌水乐园】发言
查看更多评论
添加红包
祝福语
请填写红包祝福语或标题
红包数量
个
红包个数最小为10个
红包总金额
元
红包金额最低5元
余额支付
当前余额3.43元
前往充值 >
需支付:10.00元
取消
确定
下一步
知道了
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝
规则
hope_wisdom 发出的红包
打赏作者
疯狂行者
你的鼓励将是我最大的动力
¥1
¥2
¥4
¥6
¥10
¥20
扫码支付:¥1
获取中
扫码支付
您的余额不足,请更换扫码支付或充值
打赏作者
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额
0
抵扣说明:
1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。
余额充值
CollectionUtils (Apache Commons Collections 3.2.2 API)
CollectionUtils (Apache Commons Collections 3.2.2 API)
JavaScript is disabled on your browser.
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Prev Class
Next Class
Frames
No Frames
All Classes
Summary:
Nested |
Field |
Constr |
Method
Detail:
Field |
Constr |
Method
org.apache.commons.collections
Class CollectionUtils
java.lang.Object
org.apache.commons.collections.CollectionUtils
public class CollectionUtils
extends Object
Provides utility methods and decorators for Collection instances.
Since:
Commons Collections 1.0
Version:
$Revision: 972404 $ $Date: 2015-11-07 20:44:03 +0100 (Sat, 07 Nov 2015) $
Author:
Rodney Waldhoff, Paul Jack, Stephen Colebourne, Steve Downey, Herve Quiroz, Peter KoBek, Matthew Hawthorne, Janek Bogucki, Phil Steitz, Steven Melzer, Jon Schewe, Neil O'Toole, Stephen Smith
Field Summary
Fields
Modifier and Type
Field and Description
static Collection
EMPTY_COLLECTION
An empty unmodifiable collection.
Constructor Summary
Constructors
Constructor and Description
CollectionUtils()
CollectionUtils should not normally be instantiated.
Method Summary
Methods
Modifier and Type
Method and Description
static void
addAll(Collection collection,
Enumeration enumeration)
Adds all elements in the enumeration to the given collection.
static void
addAll(Collection collection,
Iterator iterator)
Adds all elements in the iteration to the given collection.
static void
addAll(Collection collection,
Object[] elements)
Adds all elements in the array to the given collection.
static boolean
addIgnoreNull(Collection collection,
Object object)
Adds an element to the collection unless the element is null.
static int
cardinality(Object obj,
Collection coll)
Returns the number of occurrences of obj in coll.
static Collection
collect(Collection inputCollection,
Transformer transformer)
Returns a new Collection consisting of the elements of inputCollection transformed
by the given transformer.
static Collection
collect(Collection inputCollection,
Transformer transformer,
Collection outputCollection)
Transforms all elements from inputCollection with the given transformer
and adds them to the outputCollection.
static Collection
collect(Iterator inputIterator,
Transformer transformer)
Transforms all elements from the inputIterator with the given transformer
and adds them to the outputCollection.
static Collection
collect(Iterator inputIterator,
Transformer transformer,
Collection outputCollection)
Transforms all elements from the inputIterator with the given transformer
and adds them to the outputCollection.
static boolean
containsAny(Collection coll1,
Collection coll2)
Returns true iff at least one element is in both collections.
static int
countMatches(Collection inputCollection,
Predicate predicate)
Counts the number of elements in the input collection that match the predicate.
static Collection
disjunction(Collection a,
Collection b)
Returns a Collection containing the exclusive disjunction
(symmetric difference) of the given Collections.
static boolean
exists(Collection collection,
Predicate predicate)
Answers true if a predicate is true for at least one element of a collection.
static void
filter(Collection collection,
Predicate predicate)
Filter the collection by applying a Predicate to each element.
static Object
find(Collection collection,
Predicate predicate)
Finds the first element in the given collection which matches the given predicate.
static void
forAllDo(Collection collection,
Closure closure)
Executes the given closure on each element in the collection.
static Object
get(Object object,
int index)
Returns the index-th value in object, throwing
IndexOutOfBoundsException if there is no such element or
IllegalArgumentException if object is not an
instance of one of the supported types.
static Map
getCardinalityMap(Collection coll)
Returns a Map mapping each unique element in the given
Collection to an Integer representing the number
of occurrences of that element in the Collection.
static Object
index(Object obj,
int idx)
Deprecated.
use get(Object, int) instead. Will be removed in v4.0
static Object
index(Object obj,
Object index)
Deprecated.
use get(Object, int) instead. Will be removed in v4.0
static Collection
intersection(Collection a,
Collection b)
Returns a Collection containing the intersection
of the given Collections.
static boolean
isEmpty(Collection coll)
Null-safe check if the specified collection is empty.
static boolean
isEqualCollection(Collection a,
Collection b)
Returns true iff the given Collections contain
exactly the same elements with exactly the same cardinalities.
static boolean
isFull(Collection coll)
Returns true if no more elements can be added to the Collection.
static boolean
isNotEmpty(Collection coll)
Null-safe check if the specified collection is not empty.
static boolean
isProperSubCollection(Collection a,
Collection b)
Returns true iff a is a proper sub-collection of b,
that is, iff the cardinality of e in a is less
than or equal to the cardinality of e in b,
for each element e in a, and there is at least one
element f such that the cardinality of f in b
is strictly greater than the cardinality of f in a.
static boolean
isSubCollection(Collection a,
Collection b)
Returns true iff a is a sub-collection of b,
that is, iff the cardinality of e in a is less
than or equal to the cardinality of e in b,
for each element e in a.
static int
maxSize(Collection coll)
Get the maximum number of elements that the Collection can contain.
static Collection
predicatedCollection(Collection collection,
Predicate predicate)
Returns a predicated (validating) collection backed by the given collection.
static Collection
removeAll(Collection collection,
Collection remove)
Removes the elements in remove from collection.
static Collection
retainAll(Collection collection,
Collection retain)
Returns a collection containing all the elements in collection
that are also in retain.
static void
reverseArray(Object[] array)
Reverses the order of the given array.
static Collection
select(Collection inputCollection,
Predicate predicate)
Selects all elements from input collection which match the given predicate
into an output collection.
static void
select(Collection inputCollection,
Predicate predicate,
Collection outputCollection)
Selects all elements from input collection which match the given predicate
and adds them to outputCollection.
static Collection
selectRejected(Collection inputCollection,
Predicate predicate)
Selects all elements from inputCollection which don't match the given predicate
into an output collection.
static void
selectRejected(Collection inputCollection,
Predicate predicate,
Collection outputCollection)
Selects all elements from inputCollection which don't match the given predicate
and adds them to outputCollection.
static int
size(Object object)
Gets the size of the collection/iterator specified.
static boolean
sizeIsEmpty(Object object)
Checks if the specified collection/array/iterator is empty.
static Collection
subtract(Collection a,
Collection b)
Returns a new Collection containing a - b.
static Collection
synchronizedCollection(Collection collection)
Returns a synchronized collection backed by the given collection.
static void
transform(Collection collection,
Transformer transformer)
Transform the collection by applying a Transformer to each element.
static Collection
transformedCollection(Collection collection,
Transformer transformer)
Returns a transformed bag backed by the given collection.
static Collection
typedCollection(Collection collection,
Class type)
Returns a typed collection backed by the given collection.
static Collection
union(Collection a,
Collection b)
Returns a Collection containing the union
of the given Collections.
static Collection
unmodifiableCollection(Collection collection)
Returns an unmodifiable collection backed by the given collection.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Field Detail
EMPTY_COLLECTION
public static final Collection EMPTY_COLLECTION
An empty unmodifiable collection.
The JDK provides empty Set and List implementations which could be used for
this purpose. However they could be cast to Set or List which might be
undesirable. This implementation only implements Collection.
Constructor Detail
CollectionUtils
public CollectionUtils()
CollectionUtils should not normally be instantiated.
Method Detail
union
public static Collection union(Collection a,
Collection b)
Returns a Collection containing the union
of the given Collections.
The cardinality of each element in the returned Collection
will be equal to the maximum of the cardinality of that element
in the two given Collections.
Parameters:a - the first collection, must not be nullb - the second collection, must not be null
Returns:the union of the two collectionsSee Also:Collection.addAll(java.util.Collection)
intersection
public static Collection intersection(Collection a,
Collection b)
Returns a Collection containing the intersection
of the given Collections.
The cardinality of each element in the returned Collection
will be equal to the minimum of the cardinality of that element
in the two given Collections.
Parameters:a - the first collection, must not be nullb - the second collection, must not be null
Returns:the intersection of the two collectionsSee Also:Collection.retainAll(java.util.Collection),
containsAny(java.util.Collection, java.util.Collection)
disjunction
public static Collection disjunction(Collection a,
Collection b)
Returns a Collection containing the exclusive disjunction
(symmetric difference) of the given Collections.
The cardinality of each element e in the returned Collection
will be equal to
max(cardinality(e,a),cardinality(e,b)) - min(cardinality(e,a),cardinality(e,b)).
This is equivalent to
subtract(union(a,b),intersection(a,b))
or
union(subtract(a,b),subtract(b,a)).
Parameters:a - the first collection, must not be nullb - the second collection, must not be null
Returns:the symmetric difference of the two collections
subtract
public static Collection subtract(Collection a,
Collection b)
Returns a new Collection containing a - b.
The cardinality of each element e in the returned Collection
will be the cardinality of e in a minus the cardinality
of e in b, or zero, whichever is greater.
Parameters:a - the collection to subtract from, must not be nullb - the collection to subtract, must not be null
Returns:a new collection with the resultsSee Also:Collection.removeAll(java.util.Collection)
containsAny
public static boolean containsAny(Collection coll1,
Collection coll2)
Returns true iff at least one element is in both collections.
In other words, this method returns true iff the
intersection(java.util.Collection, java.util.Collection) of coll1 and coll2 is not empty.
Parameters:coll1 - the first collection, must not be nullcoll2 - the first collection, must not be null
Returns:true iff the intersection of the collections is non-emptySince:
2.1
See Also:intersection(java.util.Collection, java.util.Collection)
getCardinalityMap
public static Map getCardinalityMap(Collection coll)
Returns a Map mapping each unique element in the given
Collection to an Integer representing the number
of occurrences of that element in the Collection.
Only those elements present in the collection will appear as
keys in the map.
Parameters:coll - the collection to get the cardinality map for, must not be null
Returns:the populated cardinality map
isSubCollection
public static boolean isSubCollection(Collection a,
Collection b)
Returns true iff a is a sub-collection of b,
that is, iff the cardinality of e in a is less
than or equal to the cardinality of e in b,
for each element e in a.
Parameters:a - the first (sub?) collection, must not be nullb - the second (super?) collection, must not be null
Returns:true iff a is a sub-collection of bSee Also:isProperSubCollection(java.util.Collection, java.util.Collection),
Collection.containsAll(java.util.Collection)
isProperSubCollection
public static boolean isProperSubCollection(Collection a,
Collection b)
Returns true iff a is a proper sub-collection of b,
that is, iff the cardinality of e in a is less
than or equal to the cardinality of e in b,
for each element e in a, and there is at least one
element f such that the cardinality of f in b
is strictly greater than the cardinality of f in a.
The implementation assumes
a.size() and b.size() represent the
total cardinality of a and b, resp.
a.size() < Integer.MAXVALUE
Parameters:a - the first (sub?) collection, must not be nullb - the second (super?) collection, must not be null
Returns:true iff a is a proper sub-collection of bSee Also:isSubCollection(java.util.Collection, java.util.Collection),
Collection.containsAll(java.util.Collection)
isEqualCollection
public static boolean isEqualCollection(Collection a,
Collection b)
Returns true iff the given Collections contain
exactly the same elements with exactly the same cardinalities.
That is, iff the cardinality of e in a is
equal to the cardinality of e in b,
for each element e in a or b.
Parameters:a - the first collection, must not be nullb - the second collection, must not be null
Returns:true iff the collections contain the same elements with the same cardinalities.
cardinality
public static int cardinality(Object obj,
Collection coll)
Returns the number of occurrences of obj in coll.
Parameters:obj - the object to find the cardinality ofcoll - the collection to search
Returns:the the number of occurrences of obj in coll
find
public static Object find(Collection collection,
Predicate predicate)
Finds the first element in the given collection which matches the given predicate.
If the input collection or predicate is null, or no element of the collection
matches the predicate, null is returned.
Parameters:collection - the collection to search, may be nullpredicate - the predicate to use, may be null
Returns:the first element of the collection which matches the predicate or null if none could be found
forAllDo
public static void forAllDo(Collection collection,
Closure closure)
Executes the given closure on each element in the collection.
If the input collection or closure is null, there is no change made.
Parameters:collection - the collection to get the input from, may be nullclosure - the closure to perform, may be null
filter
public static void filter(Collection collection,
Predicate predicate)
Filter the collection by applying a Predicate to each element. If the
predicate returns false, remove the element.
If the input collection or predicate is null, there is no change made.
Parameters:collection - the collection to get the input from, may be nullpredicate - the predicate to use as a filter, may be null
transform
public static void transform(Collection collection,
Transformer transformer)
Transform the collection by applying a Transformer to each element.
If the input collection or transformer is null, there is no change made.
This routine is best for Lists, for which set() is used to do the
transformations "in place." For other Collections, clear() and addAll()
are used to replace elements.
If the input collection controls its input, such as a Set, and the
Transformer creates duplicates (or are otherwise invalid), the
collection may reduce in size due to calling this method.
Parameters:collection - the collection to get the input from, may be nulltransformer - the transformer to perform, may be null
countMatches
public static int countMatches(Collection inputCollection,
Predicate predicate)
Counts the number of elements in the input collection that match the predicate.
A null collection or predicate matches no elements.
Parameters:inputCollection - the collection to get the input from, may be nullpredicate - the predicate to use, may be null
Returns:the number of matches for the predicate in the collection
exists
public static boolean exists(Collection collection,
Predicate predicate)
Answers true if a predicate is true for at least one element of a collection.
A null collection or predicate returns false.
Parameters:collection - the collection to get the input from, may be nullpredicate - the predicate to use, may be null
Returns:true if at least one element of the collection matches the predicate
select
public static Collection select(Collection inputCollection,
Predicate predicate)
Selects all elements from input collection which match the given predicate
into an output collection.
A null predicate matches no elements.
Parameters:inputCollection - the collection to get the input from, may not be nullpredicate - the predicate to use, may be null
Returns:the elements matching the predicate (new list)
Throws:
NullPointerException - if the input collection is null
select
public static void select(Collection inputCollection,
Predicate predicate,
Collection outputCollection)
Selects all elements from input collection which match the given predicate
and adds them to outputCollection.
If the input collection or predicate is null, there is no change to the
output collection.
Parameters:inputCollection - the collection to get the input from, may be nullpredicate - the predicate to use, may be nulloutputCollection - the collection to output into, may not be null
selectRejected
public static Collection selectRejected(Collection inputCollection,
Predicate predicate)
Selects all elements from inputCollection which don't match the given predicate
into an output collection.
If the input predicate is null, the result is an empty list.
Parameters:inputCollection - the collection to get the input from, may not be nullpredicate - the predicate to use, may be null
Returns:the elements not matching the predicate (new list)
Throws:
NullPointerException - if the input collection is null
selectRejected
public static void selectRejected(Collection inputCollection,
Predicate predicate,
Collection outputCollection)
Selects all elements from inputCollection which don't match the given predicate
and adds them to outputCollection.
If the input predicate is null, no elements are added to outputCollection.
Parameters:inputCollection - the collection to get the input from, may be nullpredicate - the predicate to use, may be nulloutputCollection - the collection to output into, may not be null
collect
public static Collection collect(Collection inputCollection,
Transformer transformer)
Returns a new Collection consisting of the elements of inputCollection transformed
by the given transformer.
If the input transformer is null, the result is an empty list.
Parameters:inputCollection - the collection to get the input from, may not be nulltransformer - the transformer to use, may be null
Returns:the transformed result (new list)
Throws:
NullPointerException - if the input collection is null
collect
public static Collection collect(Iterator inputIterator,
Transformer transformer)
Transforms all elements from the inputIterator with the given transformer
and adds them to the outputCollection.
If the input iterator or transformer is null, the result is an empty list.
Parameters:inputIterator - the iterator to get the input from, may be nulltransformer - the transformer to use, may be null
Returns:the transformed result (new list)
collect
public static Collection collect(Collection inputCollection,
Transformer transformer,
Collection outputCollection)
Transforms all elements from inputCollection with the given transformer
and adds them to the outputCollection.
If the input collection or transformer is null, there is no change to the
output collection.
Parameters:inputCollection - the collection to get the input from, may be nulltransformer - the transformer to use, may be nulloutputCollection - the collection to output into, may not be null
Returns:the outputCollection with the transformed input added
Throws:
NullPointerException - if the output collection is null
collect
public static Collection collect(Iterator inputIterator,
Transformer transformer,
Collection outputCollection)
Transforms all elements from the inputIterator with the given transformer
and adds them to the outputCollection.
If the input iterator or transformer is null, there is no change to the
output collection.
Parameters:inputIterator - the iterator to get the input from, may be nulltransformer - the transformer to use, may be nulloutputCollection - the collection to output into, may not be null
Returns:the outputCollection with the transformed input added
Throws:
NullPointerException - if the output collection is null
addIgnoreNull
public static boolean addIgnoreNull(Collection collection,
Object object)
Adds an element to the collection unless the element is null.
Parameters:collection - the collection to add to, must not be nullobject - the object to add, if null it will not be added
Returns:true if the collection changed
Throws:
NullPointerException - if the collection is nullSince:
Commons Collections 3.2
addAll
public static void addAll(Collection collection,
Iterator iterator)
Adds all elements in the iteration to the given collection.
Parameters:collection - the collection to add to, must not be nulliterator - the iterator of elements to add, must not be null
Throws:
NullPointerException - if the collection or iterator is null
addAll
public static void addAll(Collection collection,
Enumeration enumeration)
Adds all elements in the enumeration to the given collection.
Parameters:collection - the collection to add to, must not be nullenumeration - the enumeration of elements to add, must not be null
Throws:
NullPointerException - if the collection or enumeration is null
addAll
public static void addAll(Collection collection,
Object[] elements)
Adds all elements in the array to the given collection.
Parameters:collection - the collection to add to, must not be nullelements - the array of elements to add, must not be null
Throws:
NullPointerException - if the collection or array is null
index
public static Object index(Object obj,
int idx)
Deprecated. use get(Object, int) instead. Will be removed in v4.0
Given an Object, and an index, returns the nth value in the
object.
If obj is a Map, returns the nth value from the keySet iterator, unless
the Map contains an Integer key with integer value = idx, in which case the
corresponding map entry value is returned. If idx exceeds the number of entries in
the map, an empty Iterator is returned.
If obj is a List or an array, returns the nth value, throwing IndexOutOfBoundsException,
ArrayIndexOutOfBoundsException, resp. if the nth value does not exist.
If obj is an iterator, enumeration or Collection, returns the nth value from the iterator,
returning an empty Iterator (resp. Enumeration) if the nth value does not exist.
Returns the original obj if it is null or not a Collection or Iterator.
Parameters:obj - the object to get an index of, may be nullidx - the index to get
Throws:
IndexOutOfBoundsException
ArrayIndexOutOfBoundsException
index
public static Object index(Object obj,
Object index)
Deprecated. use get(Object, int) instead. Will be removed in v4.0
Given an Object, and a key (index), returns the value associated with
that key in the Object. The following checks are made:
If obj is a Map, use the index as a key to get a value. If no match continue.
Check key is an Integer. If not, return the object passed in.
If obj is a Map, get the nth value from the keySet iterator.
If the Map has fewer than n entries, return an empty Iterator.
If obj is a List or an array, get the nth value, throwing IndexOutOfBoundsException,
ArrayIndexOutOfBoundsException, resp. if the nth value does not exist.
If obj is an iterator, enumeration or Collection, get the nth value from the iterator,
returning an empty Iterator (resp. Enumeration) if the nth value does not exist.
Return the original obj.
Parameters:obj - the object to get an index ofindex - the index to get
Returns:the object at the specified index
Throws:
IndexOutOfBoundsException
ArrayIndexOutOfBoundsException
get
public static Object get(Object object,
int index)
Returns the index-th value in object, throwing
IndexOutOfBoundsException if there is no such element or
IllegalArgumentException if object is not an
instance of one of the supported types.
The supported types, and associated semantics are:
Map -- the value returned is the Map.Entry in position
index in the map's entrySet iterator,
if there is such an entry.
List -- this method is equivalent to the list's get method.
Array -- the index-th array entry is returned,
if there is such an entry; otherwise an IndexOutOfBoundsException
is thrown.
Collection -- the value returned is the index-th object
returned by the collection's default iterator, if there is such an element.
Iterator or Enumeration -- the value returned is the
index-th object in the Iterator/Enumeration, if there
is such an element. The Iterator/Enumeration is advanced to
index (or to the end, if index exceeds the
number of entries) as a side effect of this method.
Parameters:object - the object to get a value fromindex - the index to get
Returns:the object at the specified index
Throws:
IndexOutOfBoundsException - if the index is invalid
IllegalArgumentException - if the object type is invalid
size
public static int size(Object object)
Gets the size of the collection/iterator specified.
This method can handles objects as follows
Collection - the collection size
Map - the map size
Array - the array size
Iterator - the number of elements remaining in the iterator
Enumeration - the number of elements remaining in the enumeration
Parameters:object - the object to get the size of
Returns:the size of the specified collection
Throws:
IllegalArgumentException - thrown if object is not recognised or nullSince:
Commons Collections 3.1
sizeIsEmpty
public static boolean sizeIsEmpty(Object object)
Checks if the specified collection/array/iterator is empty.
This method can handles objects as follows
Collection - via collection isEmpty
Map - via map isEmpty
Array - using array size
Iterator - via hasNext
Enumeration - via hasMoreElements
Note: This method is named to avoid clashing with
isEmpty(Collection).
Parameters:object - the object to get the size of, not null
Returns:true if empty
Throws:
IllegalArgumentException - thrown if object is not recognised or nullSince:
Commons Collections 3.2
isEmpty
public static boolean isEmpty(Collection coll)
Null-safe check if the specified collection is empty.
Null returns true.
Parameters:coll - the collection to check, may be null
Returns:true if empty or nullSince:
Commons Collections 3.2
isNotEmpty
public static boolean isNotEmpty(Collection coll)
Null-safe check if the specified collection is not empty.
Null returns false.
Parameters:coll - the collection to check, may be null
Returns:true if non-null and non-emptySince:
Commons Collections 3.2
reverseArray
public static void reverseArray(Object[] array)
Reverses the order of the given array.
Parameters:array - the array to reverse
isFull
public static boolean isFull(Collection coll)
Returns true if no more elements can be added to the Collection.
This method uses the BoundedCollection interface to determine the
full status. If the collection does not implement this interface then
false is returned.
The collection does not have to implement this interface directly.
If the collection has been decorated using the decorators subpackage
then these will be removed to access the BoundedCollection.
Parameters:coll - the collection to check
Returns:true if the BoundedCollection is full
Throws:
NullPointerException - if the collection is null
maxSize
public static int maxSize(Collection coll)
Get the maximum number of elements that the Collection can contain.
This method uses the BoundedCollection interface to determine the
maximum size. If the collection does not implement this interface then
-1 is returned.
The collection does not have to implement this interface directly.
If the collection has been decorated using the decorators subpackage
then these will be removed to access the BoundedCollection.
Parameters:coll - the collection to check
Returns:the maximum size of the BoundedCollection, -1 if no maximum size
Throws:
NullPointerException - if the collection is null
retainAll
public static Collection retainAll(Collection collection,
Collection retain)
Returns a collection containing all the elements in collection
that are also in retain. The cardinality of an element e
in the returned collection is the same as the cardinality of e
in collection unless retain does not contain e, in which
case the cardinality is zero. This method is useful if you do not wish to modify
the collection c and thus cannot call c.retainAll(retain);.
Parameters:collection - the collection whose contents are the target of the #retailAll operationretain - the collection containing the elements to be retained in the returned collection
Returns:a Collection containing all the elements of collection
that occur at least once in retain.
Throws:
NullPointerException - if either parameter is nullSince:
Commons Collections 3.2
removeAll
public static Collection removeAll(Collection collection,
Collection remove)
Removes the elements in remove from collection. That is, this
method returns a collection containing all the elements in c
that are not in remove. The cardinality of an element e
in the returned collection is the same as the cardinality of e
in collection unless remove contains e, in which
case the cardinality is zero. This method is useful if you do not wish to modify
the collection c and thus cannot call collection.removeAll(remove);.
Parameters:collection - the collection from which items are removed (in the returned collection)remove - the items to be removed from the returned collection
Returns:a Collection containing all the elements of collection except
any elements that also occur in remove.
Throws:
NullPointerException - if either parameter is nullSince:
Commons Collections 3.2
synchronizedCollection
public static Collection synchronizedCollection(Collection collection)
Returns a synchronized collection backed by the given collection.
You must manually synchronize on the returned buffer's iterator to
avoid non-deterministic behavior:
Collection c = CollectionUtils.synchronizedCollection(myCollection);
synchronized (c) {
Iterator i = c.iterator();
while (i.hasNext()) {
process (i.next());
}
}
This method uses the implementation in the decorators subpackage.
Parameters:collection - the collection to synchronize, must not be null
Returns:a synchronized collection backed by the given collection
Throws:
IllegalArgumentException - if the collection is null
unmodifiableCollection
public static Collection unmodifiableCollection(Collection collection)
Returns an unmodifiable collection backed by the given collection.
This method uses the implementation in the decorators subpackage.
Parameters:collection - the collection to make unmodifiable, must not be null
Returns:an unmodifiable collection backed by the given collection
Throws:
IllegalArgumentException - if the collection is null
predicatedCollection
public static Collection predicatedCollection(Collection collection,
Predicate predicate)
Returns a predicated (validating) collection backed by the given collection.
Only objects that pass the test in the given predicate can be added to the collection.
Trying to add an invalid object results in an IllegalArgumentException.
It is important not to use the original collection after invoking this method,
as it is a backdoor for adding invalid objects.
Parameters:collection - the collection to predicate, must not be nullpredicate - the predicate for the collection, must not be null
Returns:a predicated collection backed by the given collection
Throws:
IllegalArgumentException - if the Collection is null
typedCollection
public static Collection typedCollection(Collection collection,
Class type)
Returns a typed collection backed by the given collection.
Only objects of the specified type can be added to the collection.
Parameters:collection - the collection to limit to a specific type, must not be nulltype - the type of objects which may be added to the collection
Returns:a typed collection backed by the specified collection
transformedCollection
public static Collection transformedCollection(Collection collection,
Transformer transformer)
Returns a transformed bag backed by the given collection.
Each object is passed through the transformer as it is added to the
Collection. It is important not to use the original collection after invoking this
method, as it is a backdoor for adding untransformed objects.
Parameters:collection - the collection to predicate, must not be nulltransformer - the transformer for the collection, must not be null
Returns:a transformed collection backed by the given collection
Throws:
IllegalArgumentException - if the Collection or Transformer is null
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Prev Class
Next Class
Frames
No Frames
All Classes
Summary:
Nested |
Field |
Constr |
Method
Detail:
Field |
Constr |
Method
Copyright © 2001–2015 The Apache Software Foundation. All rights reserved.
Springboot内置的工具类之CollectionUtils示例讲解_springboot collectionutils.isempty-CSDN博客
>Springboot内置的工具类之CollectionUtils示例讲解_springboot collectionutils.isempty-CSDN博客
Springboot内置的工具类之CollectionUtils示例讲解
最新推荐文章于 2024-03-08 21:06:30 发布
gb4215287
最新推荐文章于 2024-03-08 21:06:30 发布
阅读量405
收藏
点赞数
分类专栏:
java
文章标签:
spring boot
spring
java
原文链接:http://www.zhano.cn/Java/68093.html
版权
java
专栏收录该内容
859 篇文章
15 订阅
订阅专栏
前言
实际业务开发中,集合的判断和操作也是经常用到的,Spring也针对集合的判断和操作封装了一些方法,但是最令我惊讶的是,我在梳理这些内容的过程中发现了一些有趣的现象,我的第一反应是不敢相信,再想一想,没错,我是对的。所以强烈建议大家可以认真看完这篇文章,这一篇绝对有价值,因为有趣的是我我竟然发现了Spring的两个bug。
org.springframework.util.CollectionUtils
集合的判断
boolean hasUniqueObject(Collection collection)
从源码注释上看,是用于判断 List/Set 中的每个元素是否唯一,即 List/Set 中不存在重复元素。但这里要告诉大家千万不要用这个方法,因为这个方法有bug,为什么呢?下面是Spring-core-5.2.13.RELEASE.jar中的源码,且看12行,细心的人会发现两个对象之间比较是否相等用的是!=。还记得“==”和“equals”的区别吗?“==”操作符专门用来比较两个变量的值是否相等,equals()方法是用于比较两个独立对象的内容是否相同。所以这里如果集合中的元素是数值,可以用“==”比较,如果是普通的引用对象,就得不到正确的结果了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public static boolean hasUniqueObject(Collection collection) { if (isEmpty(collection)) { return false; } boolean hasCandidate = false; Object candidate = null; for (Object elem : collection) { if (!hasCandidate) { hasCandidate = true; candidate = elem; } else if (candidate != elem) { return false; } } return true; }
boolean containsInstance(Collection collection, Object element)
从源码的注释上看,是用于判断集合中是否包含某个对象。这个方法也不建议使用,因为与上一个方法存在相同的问题,且看源码的第4行,依然用的是“==”。
1 2 3 4 5 6 7 8 9 10 public static boolean containsInstance(@Nullable Collection collection, Object element) { if (collection != null) { for (Object candidate : collection) { if (candidate == element) { return true; } } } return false; }
boolean isEmpty(Collection collection)
这个方法已验证过可以放心用,用于判断 List/Set 是否为空;
1 2 3 4 5 6 7 8 9 10 11 @Test public void test1(){ Collection
boolean isEmpty(Map map)
用于判断 Map 是否为空。
1 2 3 4 5 6 7 8 9 10 11 @Test public void test2(){ Map
boolean containsAny(Collection source, Collection candidates)
从源码上的注释看,是用于判断集合source中是否包含另一个集合candidates的任意一个元素,即集合candidates中的元素是否完全包含于集合soruce。
从源码这个方法中的元素之间的比较用到了“equals”方法,且调用的是集合内对象的equals方法,因此使用这个方法想要得到正确的结果的前提是,比较的对象要重写hashCode()和eauals()方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Test public void test4(){ Employee lisi = new Employee("lisi"); Employee zhangsan = new Employee("zhangsan"); Employee wangwu = new Employee("wangwu"); List
集合的操作
void mergeArrayIntoCollection(Object array, Collection collection)
将数组array中的元素都添加到 List/Set 中。
1 2 3 4 5 6 7 8 9 10 11 @Test public void test6(){ List
void mergePropertiesIntoMap(Properties props, Map map)
将 Properties 中的键值对都添加到 Map 中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Test public void test7(){ Properties properties = new Properties(); properties.setProperty("name", "zhangsan"); Map
T lastElement(List list)
返回 List 中最后一个元素。
1 2 3 4 5 6 7 8 9 10 11 12 @Test public void test9(){ Employee lisi = new Employee("lisi"); Employee zhangsan = new Employee("zhangsan"); List
T firstElement(List list)
返回集合中第一个元素。
1 2 3 4 5 6 7 @Test public void test10(){ Employee zhangsan = new Employee("zhangsan"); Employee[] employees={zhangsan}; List list = CollectionUtils.arrayToList(employees); Assert.isTrue(list.size()==1, "把数据转换成集合失败了"); }
List arrayToList(Object source)
把一个数组转换成一个集合。
1 2 3 4 5 6 7 @Test public void test10(){ Employee zhangsan = new Employee("zhangsan"); Employee[] employees={zhangsan}; List list = CollectionUtils.arrayToList(employees); Assert.isTrue(list.size()==1, "把数据转换成集合失败了"); }
到此这篇关于Springboot内置的工具类之CollectionUtils的文章就介绍到这了,更多相关Springboot内置的工具类内容请搜索站圈网以前的文章或继续浏览下面的相关文章希望大家以后多多支持站圈网!
来源:Springboot内置的工具类之CollectionUtils示例讲解_Java_站圈网_站圈网
优惠劵
gb4215287
关注
关注
0
点赞
踩
0
收藏
觉得还不错?
一键收藏
知道了
0
评论
Springboot内置的工具类之CollectionUtils示例讲解
Springboot内置的工具类之CollectionUtils示例讲解
复制链接
扫一扫
专栏目录
springboot 获取工具类bean过程详解
08-25
主要介绍了springboot 获取工具类bean过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
16 条 yyds 的代码规范
公众号:Java后端
07-27
303
作者 | 涛姐涛哥链接 |cnblogs.com/taojietaoge/p/11575376.html如何更规范化编写Java 代码Many of the happiest peopl...
参与评论
您还未登录,请先
登录
后发表或查看评论
推荐 17 个压箱底的常用类库
磊哥聊Java
05-30
588
前言在java的庞大体系中,其实有很多不错的小工具,也就是我们平常说的:轮子。如果在我们的日常工作当中,能够将这些轮子用户,再配合一下idea的快捷键,可以极大得提升我们的开发效率。今天我决定把一些压箱底的小工具,分享给大家,希望对你有所帮助。本文会分享17个我们日常工作中一定会用得到的小工具,主要内容如下:1. Collections首先出场的是java.util包下的...
Springboot中如何进行字段校验
jsxztshaohaibo的博客
07-19
2277
Hibernate Validate 进行字段校验
判断集合是否为空_spring自带的CollectionUtils工具类,集合操作原来这么简单
weixin_39855658的博客
11-29
2897
集合判断:判断集合是否为空:CollectionUtils.isEmpty(null): true CollectionUtils.isEmpty(new ArrayList()): true CollectionUtils.isEmpty({a,b}): false判断集合是否不为空:CollectionUtils.isNotEmpty(null): false CollectionUtil...
List判断为空
weixin_43652507的博客
12-31
3090
List判断为空
SpringFramework 中CollectionUtils 工具类的使用
weixin_49171365的博客
05-29
394
CollectionUtils是Spring框架中的一个工具类,提供了一系列对集合的操作方法。
Map判断为空
weixin_43652507的博客
12-31
1539
Map判断为空
盘点Spring源码中的那些判空
时间静止
12-08
1238
在平时进行判空时, 相信很多人使用的都是 org.apache.commons.lang3 的StringUtils
而我在阅读Spring源码中, 发现了一个宝藏. springframework 中自带的StringUtils, 而且也可以进行判空, 且效果一模一样!
首先我们可以看下commons包下面的StringUtils的源码, 可以看到
isEmpty() 的作用是判断输入的字符串是否为null 或者 字符串长度为0 , 例如: null, “” (空字符串)
isBlank(
commons-collections4、关于springframework的CollectionUtils包工具类介绍
m0_37910112的博客
04-14
780
【代码】commons-collections4、关于springframework的CollectionUtils包工具类介绍。
SpringBoot之自带工具类常用示例
04-29
SpringBoot之自带工具类常用示例
SpringBoot中封装jdbc工具类
04-08
现在的数据层的开发,大多会使用如MyBatis或JPA之类的开发工具。这些开发工具给我们的开发过程中带来了极大的便利。 但是在一些极端的场景下往往原生的jdbc方式操作数据库更灵活,性能更高。由于部分场景下MyBatis或...
java拓展集合工具类CollectionUtils
08-27
主要为大家详细介绍了java拓展集合工具类CollectionUtils,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
spring boot内置工具类
11-28
spring boot内置工具类。对象、数组、集合文件、资源、IO 流反射、AOP
Spring Boot与Netty的完美结合:打造高性能网络通信
最新发布
里查叔叔
03-08
561
本文介绍了如何在Spring Boot项目中添加Netty依赖、编写Netty服务端和客户端代码,并将Netty的启动和关闭整合到Spring Boot的生命周期中。一旦你整合了Netty到你的Spring Boot应用中,并实现了必要的业务逻辑处理器,你就可以构建并运行你的应用来测试Netty服务了。此外,Netty还提供了丰富的编解码器、处理器和工具类,大大简化了网络编程的复杂性。要在Spring Boot项目中集成Netty,我们需要添加Netty的依赖,并编写Netty的服务端和客户端代码。
Spring Boot搭建入门
技术分享
03-08
261
Spring Boot搭建入门
java 企业工程管理系统软件源码+Spring Cloud + Spring Boot +二次开发+ MybatisPlus + Redis
m0_72864708的博客
03-08
292
二、企业通过数字化转型,不仅有利于优化业务流程、提升经营管理能力和风险控制能力,还可强有力地促进企业体制机制的全面创新。四、在企业里建立一个管过程、提效率、降风险、控成本的工程项目管理环境,科学化、规范化是至关重要的。1、项目列表:实现对项目列表的增删改查操作,包括查看各项目的立项人、创建时间、2、项目计划管理:项目计划查看和管理模块,可执行增删改查操作,包括查看甘特图。3、收支报表:项目收支报表,包含总体收支、项目收支和收支统计模块。1、项目汇总:项目汇总信息查看,包括进度、计划时间等信息。
Spring Boot工作原理
0
03-08
1027
5、在解析@Import注解的时候,会有一个getImport()方法,从主类开始递归解析注解,把所有包含@Import的注解都解析到,然后在processImport()方法中对import的类进行分类,例如AutoConfigurationImportSelect归属于ImportSelect的子类,在后续的过程中会调用DeferredImportSelectorHandler类里面的process方法,来完成整个EnableAutoConfiguration的加载。
springboot事务工具类
11-26
以下是一个简单的SpringBoot事务工具类的示例代码: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework....
“相关推荐”对你有帮助么?
非常没帮助
没帮助
一般
有帮助
非常有帮助
提交
gb4215287
CSDN认证博客专家
CSDN认证企业博客
码龄14年
暂无认证
391
原创
1万+
周排名
530
总排名
477万+
访问
等级
3万+
积分
714
粉丝
1365
获赞
199
评论
4662
收藏
私信
关注
热门文章
如何用crontab每隔1分钟执行一个命令行脚本
116459
mysql中利用sql语句修改字段名称,字段长度等操作(亲测)
86463
Chrome模拟手机浏览器(iOS/Android)的三种方法,亲测无误!
77812
idea怎么设置自动导入包(亲测)
62093
mybatis 中 if else 用法
55576
分类专栏
idea
54篇
springboot
167篇
springcloud
50篇
mybatis
22篇
机器学习
60篇
pygame
9篇
深度学习
10篇
vue
spring
17篇
前端
1篇
dubbo
2篇
canal
1篇
pytorch
5篇
django
60篇
tomcat
6篇
hibernate
1篇
pandas
9篇
tensorflow
12篇
pycharm
8篇
streamsets
1篇
notepad
1篇
laravel
2篇
redis/memcache
96篇
mysql
192篇
linux
128篇
php
224篇
css/html
2篇
mongodb
28篇
js
9篇
jquery
3篇
shell
13篇
php多线程
6篇
编程思想
82篇
chrome
4篇
svn/git
53篇
nginx
39篇
调试工具
22篇
单元测试
1篇
流程图时序图
1篇
socketlog
1篇
sublime
12篇
大数据
15篇
支付宝生活号微信公众号
7篇
nginx+lua
23篇
lua环境
3篇
php扩展安装
10篇
nginx+lua2
16篇
压测
22篇
ngx_lua模块中的共享内存
1篇
静态化
5篇
office
高并发/秒杀
51篇
代码检测
1篇
架构
239篇
git 安装错误
6篇
gitlab
7篇
UEditor
程序人生
120篇
elk/splunk
37篇
thinkphp
26篇
shtml
1篇
连接池
3篇
算法
91篇
elasticsearch
28篇
tcp/udp
6篇
php底层
17篇
网络
21篇
https/http
2篇
mysql分库分表
9篇
go
19篇
apache
1篇
安全
6篇
webservice
3篇
数据结构
6篇
composer
4篇
hadoop
3篇
IT资讯
8篇
yaf
5篇
vmware
6篇
error
1篇
CI
2篇
mo
ice
8篇
debug
java
859篇
mq
9篇
postman
8篇
swoole
13篇
mysql高并发插入
3篇
运维工具
60篇
excel
4篇
分布式
1篇
soap
6篇
Websocket
1篇
mycat
5篇
kafka
13篇
python
246篇
C
11篇
rabbitmq
16篇
最新评论
Java Integer.equals()判断相等(亲测)
湞洋气:
f == g怎么可能是true
java接收前台tex格式t数据_java 下载文件时,设置response.setContentType 根据文件类型(亲测)
ibei023:
word格式的设置response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); 报错 java.lang.IllegalArgumentException: The Unicode character [重] at code point [37,325] cannot be encoded as it is outside the permitted range of 0 to 255
常见的10种算法(经典)
m0_64200403:
01背包不能用贪心
去除IDEA中代码的波浪线(黄色警示线)
Wwwellyyy?:
楼主好,请问设置后又重启了还是不行怎么破
java中如何压缩本地pdf文件,最好可以设置压缩率代码类实例编写?
Chr1s Harris:
哥们儿没睡醒呢
您愿意向朋友推荐“博客详情页”吗?
强烈不推荐
不推荐
一般般
推荐
强烈推荐
提交
最新文章
intellij idea如何设置控制台日志全部显示出来
RSA加密的使用
当程序员迎来 35 岁时
2024年12篇
2023年494篇
2022年233篇
2021年309篇
2020年329篇
2019年263篇
2018年226篇
2017年541篇
2016年103篇
2015年11篇
目录
目录
分类专栏
idea
54篇
springboot
167篇
springcloud
50篇
mybatis
22篇
机器学习
60篇
pygame
9篇
深度学习
10篇
vue
spring
17篇
前端
1篇
dubbo
2篇
canal
1篇
pytorch
5篇
django
60篇
tomcat
6篇
hibernate
1篇
pandas
9篇
tensorflow
12篇
pycharm
8篇
streamsets
1篇
notepad
1篇
laravel
2篇
redis/memcache
96篇
mysql
192篇
linux
128篇
php
224篇
css/html
2篇
mongodb
28篇
js
9篇
jquery
3篇
shell
13篇
php多线程
6篇
编程思想
82篇
chrome
4篇
svn/git
53篇
nginx
39篇
调试工具
22篇
单元测试
1篇
流程图时序图
1篇
socketlog
1篇
sublime
12篇
大数据
15篇
支付宝生活号微信公众号
7篇
nginx+lua
23篇
lua环境
3篇
php扩展安装
10篇
nginx+lua2
16篇
压测
22篇
ngx_lua模块中的共享内存
1篇
静态化
5篇
office
高并发/秒杀
51篇
代码检测
1篇
架构
239篇
git 安装错误
6篇
gitlab
7篇
UEditor
程序人生
120篇
elk/splunk
37篇
thinkphp
26篇
shtml
1篇
连接池
3篇
算法
91篇
elasticsearch
28篇
tcp/udp
6篇
php底层
17篇
网络
21篇
https/http
2篇
mysql分库分表
9篇
go
19篇
apache
1篇
安全
6篇
webservice
3篇
数据结构
6篇
composer
4篇
hadoop
3篇
IT资讯
8篇
yaf
5篇
vmware
6篇
error
1篇
CI
2篇
mo
ice
8篇
debug
java
859篇
mq
9篇
postman
8篇
swoole
13篇
mysql高并发插入
3篇
运维工具
60篇
excel
4篇
分布式
1篇
soap
6篇
Websocket
1篇
mycat
5篇
kafka
13篇
python
246篇
C
11篇
rabbitmq
16篇
目录
评论
被折叠的 条评论
为什么被折叠?
到【灌水乐园】发言
查看更多评论
添加红包
祝福语
请填写红包祝福语或标题
红包数量
个
红包个数最小为10个
红包总金额
元
红包金额最低5元
余额支付
当前余额3.43元
前往充值 >
需支付:10.00元
取消
确定
下一步
知道了
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝
规则
hope_wisdom 发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额
0
抵扣说明:
1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。
余额充值
Just a moment...
a moment...Enable JavaScript and cookies to contiJAVA中的最强大的工具类 CollectionUtils使用指南 - 简书
中的最强大的工具类 CollectionUtils使用指南 - 简书登录注册写文章首页下载APP会员IT技术JAVA中的最强大的工具类 CollectionUtils使用指南i小灰关注赞赏支持JAVA中的最强大的工具类 CollectionUtils使用指南 //处理工具依赖implementation 'org.apache.commons:commons-collections4:4.4'
CollectionUtils在真实项目中,是一个非常好用的工具类,使用非常频繁。它可以使代码更加简洁和安全。刚好在工作中利用这个工具类重构代码,顺便总结下分享分享:
//checking inclusion
List
List
//List1中个性元素 差集(集合相减) list1扣除list2
System.out.println(CollectionUtils.subtract(list1, list2));//[1]
//List1=2中个性元素 差集(集合相减) list1扣除list2
System.out.println(CollectionUtils.subtract(list2, list1)); //[0]
//List1、List2都个性元素 对称差集 安卓这里暂时没有这个方法
// System.out.println(CollectionUtils.symmetricDifference(set1, set2)); //[1, 0]
//List1、List2交集
System.out.println(CollectionUtils.intersection(list2, list1)); //[2, 5]
//List1、List2并集
System.out.println(CollectionUtils.union(list1, list2));//[1, 2, 5, 0]
//2个数组取交集 的补集
System.out.println(CollectionUtils.disjunction(list1, list2));//[0, 1]
//集合是否相等
System.out.println(CollectionUtils.isEqualCollection(list1,list2));//false
//集合是否不为空
System.out.println(CollectionUtils.isNotEmpty(list1));//true
//集合为空判断,与isEmpty()区别于多了null值判断,很实用
System.out.println(CollectionUtils.isEmpty(list1));//false
其他用法
emptyIfNull( coll) 如果集体为null返回一个空的集合
union( coll1, coll2) 合集
intersection( coll1, coll2) 交集
disjunction( coll1, coll2) 交集的补集
subtract( coll1, coll2) 差集
containsAll( coll1, coll2) 是否全部包含
containsAny( coll1, coll2) 是否 任一包含
isSubCollection(coll1,coll2) 是否为子集
getCardinalityMap(coll) 查询基数
filter 过滤
filterInverse 反相过滤
transform 转换
select 查询
selectRejected 反相查询
collect 投影
addIgnoreNull( collection, object) 添加 排除Null对象
addAll 合并
collate(coll1,coll2) 合并后排序
get(Object object, int index) 按下标查找,适用于:map,array,Iterator
size(Object object) 查询容器的大小,适用于:map,array,Iterator
reverseArray() 倒序
extractSingleton(collection) 取出独一值,如果集合存在多值则抛出异常
removeAll 移除所有
最后编辑于 :2021.11.17 10:32:10©著作权归作者所有,转载或内容合作请联系作者人面猴序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...沈念sama阅读 145,866评论 1赞 309死咒序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...沈念sama阅读 62,394评论 1赞 260救了他两次的神仙让他今天三更去死文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...开封第一讲书人阅读 96,852评论 0赞 214道士缉凶录:失踪的卖姜人 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...开封第一讲书人阅读 41,592评论 0赞 186港岛之恋(遗憾婚礼)正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...茶点故事阅读 49,465评论 1赞 263恶毒庶女顶嫁案:这布局不是一般人想出来的文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...开封第一讲书人阅读 39,091评论 1赞 180城市分裂传说那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...沈念sama阅读 30,669评论 2赞 279双鸳鸯连环套:你想象不到人心有多黑文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...开封第一讲书人阅读 29,435评论 0赞 172万荣杀人案实录序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...沈念sama阅读 32,820评论 0赞 217护林员之死正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...茶点故事阅读 29,534评论 2赞 221白月光启示录正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...茶点故事阅读 30,865评论 1赞 233活死人序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...沈念sama阅读 27,312评论 2赞 218日本核电站爆炸内幕正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...茶点故事阅读 31,810评论 3赞 214男人毒药:我在死后第九天来索命文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...开封第一讲书人阅读 25,703评论 0赞 9一桩弑父案,背后竟有这般阴谋文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...开封第一讲书人阅读 26,135评论 0赞 170情欲美人皮我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...沈念sama阅读 33,844评论 2赞 236代替公主和亲正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...茶点故事阅读 33,990评论 2赞 239推荐阅读更多精彩内容优雅编程之这样使用CollectionUtils,你就“正常”了(三十五)开心一笑 【公路上发生了一起车祸——乌龟踩伤了窝牛。警察正在调查事故原因说窝牛:乌龟是怎么撞 到你的?正吊着石膏的...阿_毅阅读 9,512评论 0赞 16AndroidUtilCode 最强大的工具类一、前言: AndroidUtilCode 是一个强大易用的安卓工具类库,它合理地封装了安卓开发中常用的函数,具...因为我的心阅读 37,504评论 3赞 52JS静态类型检查工具Flow使用指南TypeScript最近大火,很多人在说它与JavaScript不同之处,其中有一点必提的就是类型检查。如果我不想...SarahZ阅读 680评论 1赞 0Github 使用指南Github和Git的区别 写这篇文章的目的一来是总结下自己对于 Github 这个社区的使用经验总结;另一方面希...汤增雷阅读 981评论 0赞 10工具篇-统计Crash的工具Crashlytics使用指南前言 作为开发者,程序崩溃是很经常的事,我们可以自己利用崩溃日志和自己找出Crash的原因,但是当团队人数众多,多...進无尽阅读 9,184评论 7赞 7评论0赞11赞2赞赞赏更
CollectionUtils (Spring Framework 6.1.4 API)
CollectionUtils (Spring Framework 6.1.4 API)
JavaScript is disabled on your browser.
Skip navigation links
Spring Framework
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Summary:
Nested |
Field |
Constr |
Method
Detail:
Field |
Constr |
Method
SEARCH:
Package org.springframework.util
Class CollectionUtils
java.lang.Object
org.springframework.util.CollectionUtils
public abstract class CollectionUtils
extends Object
Miscellaneous collection utility methods.
Mainly for internal use within the framework.
Since:
1.1.3
Author:
Juergen Hoeller, Rob Harrop, Arjen Poutsma
Constructor Summary
Constructors
Constructor
Description
CollectionUtils()
Method Summary
All MethodsStatic MethodsConcrete Methods
Modifier and Type
Method
Description
static List>
arrayToList(Object source)
Convert the supplied array into a List.
static boolean
contains(Enumeration> enumeration,
Object element)
Check whether the given Enumeration contains the given element.
static boolean
contains(Iterator> iterator,
Object element)
Check whether the given Iterator contains the given element.
static boolean
containsAny(Collection> source,
Collection> candidates)
Return true if any element in 'candidates' is
contained in 'source'; otherwise returns false.
static boolean
containsInstance(Collection> collection,
Object element)
Check whether the given Collection contains the given element instance.
static Class>
findCommonElementType(Collection> collection)
Find the common element type of the given Collection, if any.
static
findFirstMatch(Collection> source,
Collection
Return the first element in 'candidates' that is contained in
'source'.
static Object
findValueOfType(Collection> collection,
Class>[] types)
Find a single value of one of the given types in the given Collection:
searching the Collection for a value of the first type, then
searching for a value of the second type, etc.
static
findValueOfType(Collection> collection,
Class
Find a single value of the given type in the given Collection.
static
firstElement(List
Retrieve the first element of the given List, accessing the zero index.
static
firstElement(Set
Retrieve the first element of the given Set, using SortedSet.first()
or otherwise using the iterator.
static boolean
hasUniqueObject(Collection> collection)
Determine whether the given Collection only contains a single unique object.
static boolean
isEmpty(Collection> collection)
Return true if the supplied Collection is null or empty.
static boolean
isEmpty(Map,?> map)
Return true if the supplied Map is null or empty.
static
lastElement(List
Retrieve the last element of the given List, accessing the highest index.
static
lastElement(Set
Retrieve the last element of the given Set, using SortedSet.last()
or otherwise iterating over all elements (assuming a linked set).
static
mergeArrayIntoCollection(Object array,
Collection
Merge the given array into the given Collection.