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 a, Iterable b)
/**
* 3、将两个已排序的集合a和b合并到一个已排序的列表中,以便保留根据Comparator c的元素顺序。
*/
CollectionUtils.collate(Iterable a, Iterable b, Comparator 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 a, Iterable b)
/**
* 10、并集
*/
CollectionUtils.union(Iterable a, Iterable 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 enumeration)
Adds all elements in the enumeration to the given collection.
static
addAll(Collection
Iterable iterable)
Adds all elements in the Iterable to the given collection.
static
addAll(Collection
Iterator 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 coll)
Deprecated.
since 4.1, use IterableUtils.frequency(Iterable, Object) instead.
Be aware that the order of parameters has changed.
static
collate(Iterable a,
Iterable 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 a,
Iterable 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 a,
Iterable b,
Comparator 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 a,
Iterable b,
Comparator 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 inputCollection,
Transformer 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 transformer)
Returns a new Collection containing all elements of the input collection
transformed by the given transformer.
static >R
collect(Iterator inputIterator,
Transformer 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 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 predicate)
Deprecated.
since 4.1, use IterableUtils.countMatches(Iterable, Predicate) instead
static
disjunction(Iterable a,
Iterable 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 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 predicate)
Filter the collection by applying a Predicate to each element.
static
filterInverse(Iterable
Predicate predicate)
Filter the collection by applying a Predicate to each element.
static
find(Iterable
Predicate 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 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 a,
Iterable 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 a,
Collection b,
Equator equator)
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
matchesAll(Iterable
Predicate predicate)
Deprecated.
since 4.1, use IterableUtils.matchesAll(Iterable, Predicate) instead
static int
maxSize(Collection 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 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 remove,
Equator 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 retain,
Equator 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 inputCollection,
Predicate predicate)
Selects all elements from input collection which match the given
predicate into an output collection.
static
select(Iterable inputCollection,
Predicate predicate,
R outputCollection)
Selects all elements from input collection which match the given
predicate and adds them to outputCollection.
static
select(Iterable inputCollection,
Predicate 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 inputCollection,
Predicate predicate)
Selects all elements from inputCollection which don't match the given
predicate into an output collection.
static
selectRejected(Iterable inputCollection,
Predicate 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 a,
Iterable b)
Returns a new Collection containing a - b.
static
subtract(Iterable a,
Iterable 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 transformer)
Transform the collection by applying a Transformer to each element.
static
transformingCollection(Collection
Transformer transformer)
Returns a transformed bag backed by the given collection.
static
union(Iterable a,
Iterable b)
Returns a Collection containing the union of the given
Iterables.
static
unmodifiableCollection(Collection 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 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)
intersection
public static
Iterable 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 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 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 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, java.lang.Iterable) 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, java.lang.Iterable) 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, java.lang.Iterable)
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, java.lang.Iterable) 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, java.lang.Iterable)
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 b,
Equator 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 inputCollection,
Transformer 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 inputIterator,
Transformer 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 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 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 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 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
collate
public static
Iterable 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 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 b,
Comparator 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 b,
Comparator 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 retain,
Equator 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 remove,
Equator 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 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 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.
static
V> void
mergePropertiesIntoMap(Properties props,
Map
Merge the given Properties instance into the given Map,
copying all properties (key-value pairs) over.
static
V> HashMap
newHashMap(int expectedSize)
Instantiate a new HashMap with an initial capacity
that can accommodate the specified number of elements without
any immediate resize/rehash operations to be expected.
static
V> LinkedHashMap
newLinkedHashMap(int expectedSize)
Instantiate a new LinkedHashMap with an initial capacity
that can accommodate the specified number of elements without
any immediate resize/rehash operations to be expected.
E extends A>A[]
toArray(Enumeration
A[] array)
Marshal the elements from the given enumeration into an array of the given type.
static
toIterator(Enumeration
Adapt an Enumeration to an Iterator.
static
V> MultiValueMap
toMultiValueMap(Map
Adapt a Map
static
V> MultiValueMap
unmodifiableMultiValueMap(MultiValueMap targetMap)
Return an unmodifiable view of the specified multi-value map.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Constructor Details
CollectionUtils
public CollectionUtils()
Method Details
isEmpty
public static boolean isEmpty(@Nullable
Collection collection)
Return true if the supplied Collection is null or empty.
Otherwise, return false.
Parameters:
collection - the Collection to check
Returns:
whether the given Collection is empty
isEmpty
public static boolean isEmpty(@Nullable
Map map)
Return true if the supplied Map is null or empty.
Otherwise, return false.
Parameters:
map - the Map to check
Returns:
whether the given Map is empty
newHashMap
public static
V> HashMap
Instantiate a new HashMap with an initial capacity
that can accommodate the specified number of elements without
any immediate resize/rehash operations to be expected.
This differs from the regular HashMap constructor
which takes an initial capacity relative to a load factor
but is effectively aligned with the JDK's
ConcurrentHashMap(int).
Parameters:
expectedSize - the expected number of elements (with a corresponding
capacity to be derived so that no resize/rehash operations are needed)
Since:
5.3
See Also:
newLinkedHashMap(int)
newLinkedHashMap
public static
V> LinkedHashMap
Instantiate a new LinkedHashMap with an initial capacity
that can accommodate the specified number of elements without
any immediate resize/rehash operations to be expected.
This differs from the regular LinkedHashMap constructor
which takes an initial capacity relative to a load factor but is
aligned with Spring's own LinkedCaseInsensitiveMap and
LinkedMultiValueMap constructor semantics as of 5.3.
Parameters:
expectedSize - the expected number of elements (with a corresponding
capacity to be derived so that no resize/rehash operations are needed)
Since:
5.3
See Also:
newHashMap(int)
arrayToList
public static List arrayToList(@Nullable
Object source)
Convert the supplied array into a List. A primitive array gets converted
into a List of the appropriate wrapper type.
NOTE: Generally prefer the standard Arrays.asList(T...) method.
This arrayToList method is just meant to deal with an incoming Object
value that might be an Object[] or a primitive array at runtime.
A null source value will be converted to an empty List.
Parameters:
source - the (potentially primitive) array
Returns:
the converted List result
See Also:
ObjectUtils.toObjectArray(Object)
Arrays.asList(Object[])
mergeArrayIntoCollection
public static
Object array,
Collection
Merge the given array into the given Collection.
Parameters:
array - the array to merge (may be null)
collection - the target Collection to merge the array into
mergePropertiesIntoMap
public static
V> void mergePropertiesIntoMap(@Nullable
Properties props,
Map
Merge the given Properties instance into the given Map,
copying all properties (key-value pairs) over.
Uses Properties.propertyNames() to even catch
default properties linked into the original Properties instance.
Parameters:
props - the Properties instance to merge (may be null)
map - the target Map to merge the properties into
contains
public static boolean contains(@Nullable
Iterator iterator,
Object element)
Check whether the given Iterator contains the given element.
Parameters:
iterator - the Iterator to check
element - the element to look for
Returns:
true if found, false otherwise
contains
public static boolean contains(@Nullable
Enumeration enumeration,
Object element)
Check whether the given Enumeration contains the given element.
Parameters:
enumeration - the Enumeration to check
element - the element to look for
Returns:
true if found, false otherwise
containsInstance
public static boolean containsInstance(@Nullable
Collection collection,
Object element)
Check whether the given Collection contains the given element instance.
Enforces the given instance to be present, rather than returning
true for an equal element as well.
Parameters:
collection - the Collection to check
element - the element to look for
Returns:
true if found, false otherwise
containsAny
public static boolean containsAny(Collection source,
Collection candidates)
Return true if any element in 'candidates' is
contained in 'source'; otherwise returns false.
Parameters:
source - the source Collection
candidates - the candidates to search for
Returns:
whether any of the candidates has been found
findFirstMatch
@Nullable
public static
Collection
Return the first element in 'candidates' that is contained in
'source'. If no element in 'candidates' is present in
'source' returns null. Iteration order is
Collection implementation specific.
Parameters:
source - the source Collection
candidates - the candidates to search for
Returns:
the first present object, or null if not found
findValueOfType
@Nullable
public static
@Nullable
Class
Find a single value of the given type in the given Collection.
Parameters:
collection - the Collection to search
type - the type to look for
Returns:
a value of the given type found if there is a clear match,
or null if none or more than one such value found
findValueOfType
@Nullable
public 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.
Parameters:
collection - the collection to search
types - the types to look for, in prioritized order
Returns:
a value of one of the given types found if there is a clear match,
or null if none or more than one such value found
hasUniqueObject
public static boolean hasUniqueObject(Collection collection)
Determine whether the given Collection only contains a single unique object.
Parameters:
collection - the Collection to check
Returns:
true if the collection contains a single reference or
multiple references to the same instance, false otherwise
findCommonElementType
@Nullable
public static Class findCommonElementType(Collection collection)
Find the common element type of the given Collection, if any.
Parameters:
collection - the Collection to check
Returns:
the common element type, or null if no clear
common type has been found (or the collection was empty)
firstElement
@Nullable
public static
Set
Retrieve the first element of the given Set, using SortedSet.first()
or otherwise using the iterator.
Parameters:
set - the Set to check (may be null or empty)
Returns:
the first element, or null if none
Since:
5.2.3
See Also:
SortedSet
LinkedHashMap.keySet()
LinkedHashSet
firstElement
@Nullable
public static
List
Retrieve the first element of the given List, accessing the zero index.
Parameters:
list - the List to check (may be null or empty)
Returns:
the first element, or null if none
Since:
5.2.3
lastElement
@Nullable
public static
Set
Retrieve the last element of the given Set, using SortedSet.last()
or otherwise iterating over all elements (assuming a linked set).
Parameters:
set - the Set to check (may be null or empty)
Returns:
the last element, or null if none
Since:
5.0.3
See Also:
SortedSet
LinkedHashMap.keySet()
LinkedHashSet
lastElement
@Nullable
public static
List
Retrieve the last element of the given List, accessing the highest index.
Parameters:
list - the List to check (may be null or empty)
Returns:
the last element, or null if none
Since:
5.0.3
toArray
E extends A> A[] toArray(Enumeration
A[] array)
Marshal the elements from the given enumeration into an array of the given type.
Enumeration elements must be assignable to the type of the given array. The array
returned will be a different instance than the array given.
toIterator
public static
Enumeration
Adapt an Enumeration to an Iterator.
Parameters:
enumeration - the original Enumeration
Returns:
the adapted Iterator
toMultiValueMap
public static
V> MultiValueMap
Adapt a Map
Parameters:
targetMap - the original map
Returns:
the adapted multi-value map (wrapping the original map)
Since:
3.1
unmodifiableMultiValueMap
public static
V> MultiValueMap
Return an unmodifiable view of the specified multi-value map.
Parameters:
targetMap - the map for which an unmodifiable view is to be returned.
Returns:
an unmodifiable view of the specified multi-value map
Since:
3.1
java基础|CollectionUtils工具的基本使用-腾讯云开发者社区-腾讯云
基础|CollectionUtils工具的基本使用-腾讯云开发者社区-腾讯云码农王同学java基础|CollectionUtils工具的基本使用关注作者腾讯云开发者社区文档建议反馈控制台首页学习活动专区工具TVP最新优惠活动文章/答案/技术大牛搜索搜索关闭发布登录/注册首页学习活动专区工具TVP最新优惠活动返回腾讯云官网码农王同学首页学习活动专区工具TVP最新优惠活动返回腾讯云官网社区首页 >专栏 >java基础|CollectionUtils工具的基本使用java基础|CollectionUtils工具的基本使用码农王同学关注发布于 2020-08-25 11:23:361.2K0发布于 2020-08-25 11:23:36举报文章被收录于专栏:后端Coder后端Coder 对于java后端来说,和集合打交道无处不在,对于集合的一些操作,这里自己总结一下,便于以后看的时候也能想起来。package com.wpw.springbootjuc.java8.map;import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import java.util.List;
/**
* CollectionUtils工具的使用总结
*
* @author wpw
*/
@Slf4j
public class CollectionUtilsTest {
private static final List
private static final List
static {
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(5);
arrayList.add(6);
arrayList.add(7);
arrayList.add(8);
arrayList.add(9);
arrayList.add(10);
}
static {
arrayListNew.add(1);
arrayListNew.add(2);
arrayListNew.add(3);
arrayListNew.add(4);
arrayListNew.add(5);
arrayListNew.add(6);
arrayListNew.add(7);
arrayListNew.add(8);
arrayListNew.add(9);
arrayListNew.add(10);
}
public static void main(String[] args) {
log.info("判断集合是否为空:[{}]", CollectionUtils.isEmpty(arrayList));
log.info("判断集合是否不为空:[{}]", !CollectionUtils.isEmpty(arrayListNew));
log.info("获取集合的大小数据:[{}]", arrayList.size());
log.info("数组转为集合然后进行循环遍历输出");
List list = CollectionUtils.arrayToList(new Integer[]{1, 2, 3, 4});
list.stream().forEach(x -> System.out.print(x + "\t"));
//本来想着用CollectionUtils测试类,觉得spring提供的方法还是太少了
//这里用下lang3提供的字符串判断工具看下吧
log.info("判断字符串是否为null:[{}]",StringUtils.isEmpty(null));
String trimStr="a b c d ";
String str = StringUtils.trim(trimStr);
System.out.println("str = " + str);
}
}
复制这个工具没有实际场景不是很好用,先暂时做个介绍好了,到这里就结束了。
本文参与 腾讯云自媒体分享计划,分享自微信公众号。原始发表:2020-08-20,如有侵权请联系 cloudcommunity@tencent.com 删除java工具后端集合本文分享自 码农王同学 微信公众号,前往查看如有侵权,请联系 cloudcommunity@tencent.com 删除。本文参与 腾讯云自媒体分享计划 ,欢迎热爱写作的你一起参与!java工具后端集合评论登录后参与评论0 条评论热度最新登录 后参与评论推荐阅读LV.关注文章0获赞0领券社区专栏文章阅读清单互动问答技术沙龙技术视频团队主页腾讯云TI平台活动自媒体分享计划邀请作者入驻自荐上首页技术竞赛资源技术周刊社区标签开发者手册开发者实验室关于社区规范免责声明联系我们友情链接腾讯云开发者扫码关注腾讯云开发者领取腾讯云代金券热门产品域名注册云服务器区块链服务消息队列网络加速云数据库域名解析云存储视频直播热门推荐人脸识别腾讯会议企业云CDN加速视频通话图像分析MySQL 数据库SSL 证书语音识别更多推荐数据安全负载均衡短信文字识别云点播商标注册小程序开发网站监控数据迁移Copyright © 2013 - 2024 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有 深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档Copyright © 2013 - 2024 Tencent Cloud.All Rights Reserved. 腾讯云 版权所有登录 后参与评论00
apache commons collections CollectionUtils工具类简单使用_collectionutil工具类 common-CSDN博客
>apache commons collections CollectionUtils工具类简单使用_collectionutil工具类 common-CSDN博客
apache commons collections CollectionUtils工具类简单使用
最新推荐文章于 2024-03-08 05:17:42 发布
@sky@
最新推荐文章于 2024-03-08 05:17:42 发布
阅读量3.5k
收藏
7
点赞数
2
分类专栏:
工具
文章标签:
java
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/dgzhang_reg/article/details/107931883
版权
工具
专栏收录该内容
1 篇文章
0 订阅
订阅专栏
一. CollectionUtils提供很多对集合的操作方法,常用的方法如下:
集合判断: 例1: 判断集合是否为空: CollectionUtils.isEmpty(null): true CollectionUtils.isEmpty(new ArrayList()): true CollectionUtils.isEmpty({a,b}): false
例2: 判断集合是否不为空: CollectionUtils.isNotEmpty(null): false CollectionUtils.isNotEmpty(new ArrayList()): false CollectionUtils.isNotEmpty({a,b}): true
例3 2个集合间的操作: 集合a: {1,2,3,3,4,5} 集合b: {3,4,4,5,6,7} CollectionUtils.union(a, b)(并集): {1,2,3,3,4,4,5,6,7} CollectionUtils.intersection(a, b)(交集): {3,4,5} CollectionUtils.disjunction(a, b)(交集的补集): {1,2,3,4,6,7} CollectionUtils.disjunction(b, a)(交集的补集): {1,2,3,4,6,7} CollectionUtils.subtract(a, b)(A与B的差): {1,2,3} CollectionUtils.subtract(b, a)(B与A的差): {4,6,7}
代码如下:
package collections_utils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @Package: collections_utils
* @ClassName: TestCollectionUtils
* @Author: ZDG
* @Date: 2020/8/11 11:37
*/
public class TestCollectionUtils {
private final static String[] arrayA = new String[]{"A", "B", "C", "D", "E", "F"};
private final static String[] arrayB = new String[]{"B", "D", "F", "G", "H", "K"};
@Test //并集
public void testUnion() {
// 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 testIntersection() {
// 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 testDisjunction() {
// 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 testSubtract() {
//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与B的差
//[A, C, E]
System.out.println(ArrayUtils.toString(CollectionUtils.subtract(listB, listA))); //B与A的差
//[G,H,K]
}
@Test //集合是否为空
public void testIsEmpty(){
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 testIsEqual(){
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
/*
* boy1.add(new Girl());
*
* boy2.add(new Girl());
*
* new 的地址址不一样的
*
* */
List
//每个男孩心里都装着一个女孩
boy3.add(goldGirl);
List
boy4.add(goldGirl);
System.out.println(CollectionUtils.isEqualCollection(boy3,boy4)); //true
}
/*
不可修改的集合
我们对c进行操作,s也同样获得了和c相同的内容,这样就可以避免其他人员修改这个s对象。
有时候需要对它进行保护,避免返回结果被人修改。
*/
@Test
public void testUnmodifiableCollection(){
Collection
Collection
c.add("boy");
c.add("love");
c.add("girl");
//! s.add("have a error"); //s 不可被修改的
System.out.println(s);
}
/*
Collections.unmodifiableCollection可以得到一个集合的镜像,它的返回结果是不可直接被改变,否则会提示错误
java.lang.UnsupportedOperationException
at org.apache.commons.collections.collection.UnmodifiableCollection.add(UnmodifiableCollection.java:75)
*/
}
依赖坐标: 点击下载jar
maven
gradle
// https://mvnrepository.com/artifact/commons-collections/commons-collections
compile group: 'commons-collections', name: 'commons-collections', version: '3.2.2'
优惠劵
@sky@
关注
关注
2
点赞
踩
7
收藏
觉得还不错?
一键收藏
知道了
0
评论
apache commons collections CollectionUtils工具类简单使用
一. CollectionUtils提供很多对集合的操作方法,常用的方法如下:集合判断:例1: 判断集合是否为空:CollectionUtils.isEmpty(null): trueCollectionUtils.isEmpty(new ArrayList()): trueCollectionUtils.isEmpty({a,b}): false例2: 判断集合是否不为空:CollectionUtils.isNotEmpty(null): falseCollectionUtils.i
复制链接
扫一扫
专栏目录
apache-commons源码及jar文件
02-28
Apache Commons是一个非常有用的工具包,解决各种实际的通用问题。(附件中提供了该工具包的jar包,及源文件以供研究)
BeanUtils
Commons-BeanUtils 提供对 Java 反射和自省API的包装
Betwixt
Betwixt提供将 JavaBean 映射至 XML 文档,以及相反映射的服务.
Chain
Chain 提供实现组织复杂的处理流程的“责任链模式”.
CLI
CLI 提供针对命令行参数,选项,选项组,强制选项等的简单API.
Codec
Codec 包含一些通用的编码解码算法。包括一些语音编码器, Hex, Base64, 以及URL encoder.
Collections
Commons-Collections 提供一个类包来扩展和增加标准的 Java Collection框架
Configuration
Commons-Configuration 工具对各种各式的配置和参考文件提供读取帮助.
Daemon
一种 unix-daemon-like java 代码的替代机制
DBCP
Commons-DBCP 提供数据库连接池服务
DbUtils
DbUtils 是一个 JDBC helper 类库,完成数据库任务的简单的资源清除代码.
Digester
Commons-Digester 是一个 XML-Java对象的映射工具,用于解析 XML配置文件.
Discovery
Commons-Discovery 提供工具来定位资源 (包括类) ,通过使用各种模式来映射服务/引用名称和资源名称。.
EL
Commons-EL 提供在JSP2.0规范中定义的EL表达式的解释器.
FileUpload
FileUpload 使得在你可以在应用和Servlet中容易的加入强大和高性能的文件上传能力
HttpClient
Commons-HttpClient 提供了可以工作于HTTP协议客户端的一个框架.
IO
IO 是一个 I/O 工具集
Jelly
Jelly是一个基于 XML 的脚本和处理引擎。 Jelly 借鉴了 JSP 定指标签,Velocity, Cocoon和Xdoclet中的脚本引擎的许多优点。Jelly 可以用在命令行, Ant 或者 Servlet之中。
Jexl
Jexl是一个表达式语言,通过借鉴来自于Velocity的经验扩展了JSTL定义的表达式语言。.
JXPath
Commons-JXPath 提供了使用Xpath语法操纵符合Java类命名规范的 JavaBeans的工具。也支持 maps, DOM 和其他对象模型。.
Lang
Commons-Lang 提供了许多许多通用的工具类集,提供了一些java.lang中类的扩展功能
Latka
Commons-Latka 是一个HTTP 功能测试包,用于自动化的QA,验收和衰减测试.
Launcher
Launcher 组件是一个交叉平台的Java 应用载入器。 Commons-launcher 消除了需要批处理或者Shell脚本来载入Java 类。.原始的 Java 类来自于Jakarta Tomcat 4.0 项目
Logging
Commons-Logging 是一个各种 logging API实现的包裹类.
Math
Math 是一个轻量的,自包含的数学和统计组件,解决了许多非常通用但没有及时出现在Java标准语言中的实践问题.
Modeler
Commons-Modeler 提供了建模兼容JMX规范的 Mbean的机制.
Net
Net 是一个网络工具集,基于 NetComponents 代码,包括 FTP 客户端等等。
Pool
Commons-Pool 提供了通用对象池接口,一个用于创建模块化对象池的工具包,以及通常的对象池实现.
Primitives
Commons-Primitives提供了一个更小,更快和更易使用的对Java基本类型的支持。当前主要是针对基本类型的 collection。.
Validator
The commons-validator提供了一个简单的,可扩展的框架来在一个XML文件中定义校验器 (校验方法)和校验规则。支持校验规则的和错误消息的国际化。
CollectionUtils的大体用法
Salted_fish_master的博客
05-12
421
CollectionsUtils是对集合进行操作,别弄错成数组了返回类型是一个新的集合CollectionUtils.union(List<T> a,List<T> b);//并集CollectionUtils.intersection(List<T> a,List<T> b);//交集CollectionUtils.disjunction(List...
参与评论
您还未登录,请先
登录
后发表或查看评论
Apache Commons 工具类介绍及简单使用
蔡小兵的博客
05-03
566
Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动。下面是我这几年做开发过程中自己用过的工具类做简单介绍。
组件
功能介绍
BeanUtils
提供了对于JavaBean进行各种操作,克隆对象,属性等等.
Betwixt
XML与Java对象之间相互转换.
Codec
处理常用的编码方法的工具类包例如DES...
集合工具类 - CollectionUtil.java
cx136295988的博客
07-25
999
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.collectio
CollectionUtil集合工具类
qq_43502453的博客
04-29
1545
package com.uama.utils;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
impo
Java猿社区—Apache Commons Collections—CollectionUtils工具类详解
竹林幽深
08-06
3287
欢迎关注作者博客简书传送门
文章目录
前言
代码示例
前言
论阅读源码的重要性,后期会对各大开源框架相关源码做详细阅读,并熟悉使用,本次主要对Apache Commons Collections中CollectionUtils类进行示例分析,如有错误,请多指教。
通过apache-commons包中的org.apache.commons.collections.CollectionUtils集合操作工具类 对集合间进行合并union、交叉int..
集合工具类 org.apache.commons.collections.CollectionUtils
09-24
5944
import org.apache.commons.collections.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class CollectionUtilsTest {
public static void main(String[] args) {
List
org.apache.commons.collections.CollectionUtils
Love Cafe, Love Java
04-14
1227
集合判断:
例1: 判断集合是否为空:
CollectionUtils.isEmpty(null): true
CollectionUtils.isEmpty(new ArrayList()): true
CollectionUtils.isEmpty({a,b}): false
例2: 判断集合是否不为空:
CollectionUtils.isNotEmpty(null): fa...
CollectionUtils工具类的常用方法
weixin_34067049的博客
09-10
218
集合判断: 例1: 判断集合是否为空: CollectionUtils.isEmpty(null): true CollectionUtils.isEmpty(new ArrayList()): true CollectionUtils.isEmpty({a,b}): false 例2: 判断集合是否不为空: CollectionU...
commons-collections-3.2.jar - Java包下载页
05-21
这是commons-collections-3.2.jar的下载,它是commons中各集合类和工具类的封装包。因为commons-collections有很多版本,每个版本的环境又有些不同,所以版本对应是最好的,有需要3.2版本的可下载
Jakarta commons docs API CHM 格式
09-13
commons-discovery 提供工具来定位资源 (包括类) ,通过使用各种模式来映射服务/引用名称和资源名称。 commons-el 提供在JSP2.0规范中定义的EL表达式的解释器. commons-email 提供一组用于发送Email的API,它基于...
比较全面的:Jakarta-commons jar包(附: chm参考手册 & 资源简介)
05-23
commons-discovery 提供工具来定位资源 (包括类) ,通过使用各种模式来映射服务/引用名称和资源名称。 commons-el 提供在JSP2.0规范中定义的EL表达式的解释器. commons-email 提供一组用于发送Email的API,它基于...
ysoserial:概念证明工具,用于生成利用不安全的Java对象反序列化的有效负载
05-12
最初作为AppSecCali 2015讲座一部分发布,其中包含针对Apache Commons Collections(3.x和4.x),Spring Beans / Core(4.x)和Groovy( 2.3.x)。 后来进行了更新,以包括其他小工具链和其他几个库。 ysoserial是...
重学SpringBoot3-yaml文件配置
CoderJia的学习之路
03-05
1108
YAML 提供了一种更为人性化的配置文件格式,它通过简洁的结构化格式,使得配置信息更加易于理解和维护。在 Spring Boot 中,通过使用 YAML,开发者可以轻松地管理和切换不同环境下的配置,优化开发流程。掌握 YAML 的基本写法和在 Spring Boot 中的应用,将有助于提高你的开发效率。
Java集合5-HashSet
wujianyouhun的专栏
03-05
496
HashSet的原理比较简单,几乎全部借助于HashMap来实现的。由于 HashSet 的底层是基于 HashMap 实现的,因此具有 HashMap 的特性,如高效的添加、查找操作(平均情况下为 O(1)),去重功能等。不过需要注意的是,HashSet 并不保证元素的顺序,元素存储的顺序与插入顺序可能不同,因为它是根据哈希值存储的。所以HashMap会出现的问题HashSet依然不能避免。
Java的 Map以及实现一个简单的红黑树
好看的皮囊千篇一律,有趣的灵魂万里挑一。
03-07
1100
Map是将键映射到值的对象。map**不能包含重复的键**; 每个键最多只能映射到一个值。这个接口取代了Dictionary类,Dictionary类是一个完全抽象的类,而不是接口。
Map接口提供了三个集合视图,它们允许将映射的内容视为一组键、一组值或一组键-值映射。映射的顺序定义为映射集合视图上的迭代器返回其元素的顺序。一些类似实现,比如TreeMap类,对它们的顺序做出了特定的保证;其他类,如HashMap类,则不需要。
注意:如果使用可变对象作为映射键,必须非常小心。如果对象的值以影响相等比较的
数组的访问2
程小白的博客
03-07
222
/ 数组的长度// 非空数组的最大索引 = array.length - 1。
安卓Java面试题 31-40
最新发布
我很好
03-08
118
比如说子线程更新UI,是因为触发了checkThread方法检查是否在主线程更新UI,还有就是子线程中没有Looper,这个原因是因为Handler的机制引起的,因为Handler发送Message的时候,需要将Message放到MessageQueue里面,而这个时候如果没有Looper的话,就无法循环输出MessageQueue了,这个时候就会报Looper为空的错误。7.套接字(socket ) : 套解字也是一种进程间通信机制,与其他通信机制不同的是,它可用于不同及其间的进程通信。
ListUtils.splitList() 可以使用 Apache Commons Collections 库中的工具类实现
05-26
是的,Apache Commons Collections 库中的 ListUtils 类提供了 splitList() 方法,可以将一个列表按照指定大小拆分成多个子列表。以下是使用 ListUtils.splitList() 实现拆分列表的示例代码:
```java
import org.apache.commons.collections4.ListUtils;
import java.util.List;
public class Example {
public static void main(String[] args) {
List
List> subLists = ListUtils.partition(list, 3);
System.out.println(subLists); // [[1, 2, 3], [4, 5, 6]]
}
}
```
在上面的示例代码中,我们首先使用 List.of() 创建了一个包含 6 个整数的列表。然后,我们使用 ListUtils.partition() 方法将该列表按照大小为 3 的子列表进行拆分,最终得到了一个包含两个子列表的列表。
“相关推荐”对你有帮助么?
非常没帮助
没帮助
一般
有帮助
非常有帮助
提交
@sky@
CSDN认证博客专家
CSDN认证企业博客
码龄5年
暂无认证
9
原创
91万+
周排名
121万+
总排名
1万+
访问
等级
130
积分
0
粉丝
8
获赞
3
评论
25
收藏
私信
关注
热门文章
hutool导出导出excel中文自适应列宽+反射+自定义注解获取表头
5318
springboot 获取enviroment.Properties的几种方式
5119
apache commons collections CollectionUtils工具类简单使用
3502
IDEA 黑色主题很难看到鼠标
1327
quartz定时任务时间设置
598
分类专栏
date
工具
1篇
Random
CollectionUtil
CollectionUtils
rabbitmq
SpringBoot启动器
JDBC
最大连接数
Groovy正则处理String
webservice
sql语句大全
并发问题的解决
dom4j
插入/更新数据
CSDN编辑
最新评论
hutool导出导出excel中文自适应列宽+反射+自定义注解获取表头
Aaron逸飞:
这个支持多个表页吗
您愿意向朋友推荐“博客详情页”吗?
强烈不推荐
不推荐
一般般
推荐
强烈推荐
提交
最新文章
IDEA 黑色主题很难看到鼠标
hutool导出导出excel中文自适应列宽+反射+自定义注解获取表头
Java经典递归算法
2022年2篇
2021年4篇
2020年3篇
目录
目录
分类专栏
date
工具
1篇
Random
CollectionUtil
CollectionUtils
rabbitmq
SpringBoot启动器
JDBC
最大连接数
Groovy正则处理String
webservice
sql语句大全
并发问题的解决
dom4j
插入/更新数据
CSDN编辑
目录
评论
被折叠的 条评论
为什么被折叠?
到【灌水乐园】发言
查看更多评论
添加红包
祝福语
请填写红包祝福语或标题
红包数量
个
红包个数最小为10个
红包总金额
元
红包金额最低5元
余额支付
当前余额3.43元
前往充值 >
需支付:10.00元
取消
确定
下一步
知道了
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝
规则
hope_wisdom 发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额
0
抵扣说明:
1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。
余额充值