public final class CollectionsUtil extends Object
Collection
工具类,是 Collections
的扩展和补充.
Collection
:
字段 说明 Collection
List
:
interface/class 说明 List
- An ordered collection
- integer index for insert and search.
- 除了继承Collection接口方法外,有自己的方法定义: get(int) indexOf lastIndexOf listIterator set(int) subList(int,int)
- optional:可空,可重复
ArrayList
- Resizable-array implementation of the List interface
- 元素可空
- 有自己控制容量(数组大小)的方法
扩容:
- see
ArrayList.ensureCapacity(int)
,
在jdk1.6里面,int newCapacity = (oldCapacity * 3)/2 + 1 通常是1.5倍
在jdk1.7+里面,代码进行了优化LinkedList
- Linked list implementation,双向链表
- 元素可空
Vector
- growable array of objects
- 线程安全的动态数组 synchronized
- 操作基本和ArrayList相同
Stack
- last-in-first-out (LIFO) stack of objects
Set
:
interface/class 说明 Set
- A collection contains no duplicate elements
- Set和Collection拥有一模一样的接口名称
HashSet
- backed by a HashMap instance.
- makes no guarantees as to the iteration order of the set; 不保证顺序
- permits the null element.允许空元素
LinkedHashSet
- Hash Map and linked list implementation of the Set interface,
- with predictable iteration order
TreeSet
- A NavigableSet implementation based on a TreeMap.
- ordered using their natural ordering, or by a Comparator provided at set creation time
EnumSet
- A specialized Set implementation for use with enum types.
- Null elements are not permitted.
- natural order (the order in which the enum constants are declared.
- abstract class.
- 以位向量的形式存储,这种存储形式非常紧凑,高效,占用内存很小,运行效率很好.
Queue
:
interface/class 说明 Queue
- Queues typically, but do not necessarily,order elements in a FIFO (first-in-first-out) manner
- 天下人都知道Set,Map不能重复
- 80%人知道hashCode,equals是判断重复的法则
- 40%人知道Set添加重复元素时,旧元素不会被覆盖
- 20%人知道Map添加重复键时,旧键不会被覆盖,而值会覆盖
- com.google.common.collect.Iterables.concat(
Iterable<? extends Iterable<? extends T>>
)
Collections
,
ListUtils
,
IterableUtils
,
CollectionUtils
,
"org.springframework.util.CollectionUtils",
"com.google.common.collect.Sets",
"com.google.common.collect.Lists",
"com.google.common.collect.Queues",
"com.google.common.collect.Iterators",
"com.google.common.collect.Iterables"Modifier and Type | Method and Description |
---|---|
static <O> boolean |
addAllIgnoreNull(Collection<O> objectCollection,
Iterable<? extends O> iterable)
|
static <T> boolean |
addIgnoreNullOrEmpty(Collection<T> objectCollection,
T element)
添加
element 元素到指定的objectCollection ,如果 element 是null或者 empty将忽略. |
static <O,I> List<O> |
collect(Iterable<I> inputBeanIterable,
Class<O> outputListBeanType,
String... includePropertyNames)
循环
inputBeanIterable ,将每个元素使用转换程成新的 outputListBeanType 类型对象(如有需要只copy传入的includePropertyNames 属性)
返回新的list. |
static <O,T> List<T> |
collect(Iterable<O> inputIterable,
Transformer<? super O,? extends T> transformer)
循环
inputIterable ,将每个元素使用 transformer 转换成新的对象,返回新的list. |
static <O,T> List<T> |
collect(Iterator<O> inputIterator,
Transformer<? super O,? extends T> transformer)
循环
inputIterator ,将每个元素使用 transformer 转换成新的对象 返回新的list. |
static <O> O |
find(Iterable<O> iterable,
Predicate<O> predicate)
迭代查找匹配
predicate 的第一个元素并返回. |
static <O,V> O |
find(Iterable<O> beanIterable,
String propertyName,
V propertyValue)
找到
iterable 中,第一个 propertyName 属性名称值是 propertyValue 的对应元素. |
static <O> void |
forEach(Iterable<O> beanIterable,
String propertyName,
Object propertyValue)
循环将
beanIterable 每个元素的每个指定属性 propertyName 的值改成 propertyValue . |
static <T,O> List<T> |
getPropertyValueList(Iterable<O> beanIterable,
String propertyName)
|
static <K,V,O> Map<K,V> |
getPropertyValueMap(Iterable<O> beanIterable,
String keyPropertyName,
String valuePropertyName)
循环
beanIterable ,以 keyPropertyName 属性值为key, valuePropertyName 属性值为value,组成map返回. |
static <T,O> Set<T> |
getPropertyValueSet(Iterable<O> beanIterable,
String propertyName)
|
static <T,O> Map<T,List<O>> |
group(Iterable<O> beanIterable,
Predicate<O> includePredicate,
Transformer<O,T> keyTransformer)
循环
beanIterable ,找到符合条件的 includePredicate 的元素,将元素使用keyTransformer 转成key
,相同值的元素组成list作为value,封装成map返回. |
static <T,O> Map<T,List<O>> |
group(Iterable<O> beanIterable,
String propertyName)
循环
beanIterable ,以 元素的 propertyName 属性值为key,相同值的元素组成list作为value,封装成map返回. |
static <T,O> Map<T,List<O>> |
group(Iterable<O> beanIterable,
String propertyName,
Predicate<O> includePredicate)
循环
beanIterable ,找到符合条件的 includePredicate 的元素,以元素的 propertyName
属性值为key,相同值的元素组成list作为value,封装成map返回. |
static <T,O> Map<T,List<O>> |
group(Iterable<O> beanIterable,
Transformer<O,T> keyTransformer)
循环
beanIterable ,将元素使用keyTransformer 转成key,相同值的元素组成list作为value,封装成map返回. |
static <T,O> Map<T,O> |
groupOne(Iterable<O> beanIterable,
String propertyName)
循环
iterable ,以元素的 propertyName 属性值为key,元素为value,封装成map返回(map只put第一个匹配的元素,后面出现相同的元素将会忽略). |
static <O,V> int |
indexOf(List<O> list,
String propertyName,
V propertyValue)
在
list 中,查找第一个属性 propertyName 值是指定值 propertyValue 对象的索引位置. |
static <E> ArrayList<E> |
newArrayList()
创建 a mutable, empty
ArrayList instance . |
static <E> CopyOnWriteArrayList<E> |
newCopyOnWriteArrayList()
创建 a mutable, empty
CopyOnWriteArrayList instance . |
static <E> HashSet<E> |
newHashSet()
创建 a mutable, empty
newHashSet instance . |
static <E> LinkedHashSet<E> |
newLinkedHashSet()
创建 a mutable, empty
LinkedHashSet instance . |
static <E> LinkedList<E> |
newLinkedList()
创建 a mutable, empty
LinkedList instance . |
static <O> List<O> |
remove(Collection<O> objectCollection,
O... removeElements)
从
objectCollection 中 删除removeElements (原集合对象不变). |
static <O> List<O> |
removeAll(Collection<O> objectCollection,
Collection<O> removeCollection)
从
objectCollection 中删除所有的 removeCollection (原集合对象不变). |
static <O> List<O> |
removeAllNull(Collection<O> objectCollection)
从
objectCollection 中删除所有的 null 元素 (原集合对象不变). |
static <O> List<O> |
removeDuplicate(Collection<O> objectCollection)
去重,返回没有重复元素的新list (原集合对象不变).
|
static <O> List<O> |
select(Iterable<O> beanIterable,
Predicate<O> predicate)
按照指定的
Predicate ,返回查询出来的集合. |
static <O,V> List<O> |
select(Iterable<O> beanIterable,
String propertyName,
Collection<V> propertyValueList)
循环
beanIterable ,获得元素 bean 的propertyName 的值,判断是否在propertyValueList
集合中;如果在,将该对象存入list中返回. |
static <O,V> List<O> |
select(Iterable<O> beanIterable,
String propertyName,
V... propertyValues)
循环
beanIterable ,获得元素 bean 的 propertyName 的值,判断是否在propertyValues
数组中;如果在,将该对象存入list中返回. |
static <O> List<O> |
selectRejected(Iterable<O> beanIterable,
Predicate<O> predicate)
循环
beanIterable ,获得元素 bean ,判断是否不匹配predicate ,如果不匹配
,将该对象存入list中返回. |
static <O,V> List<O> |
selectRejected(Iterable<O> beanIterable,
String propertyName,
Collection<V> propertyValueList)
循环
beanIterable ,获得元素 bean 的 propertyName 的值,判断是否不在propertyValueList
集合中;如果不在,将该对象存入list中返回. |
static <O,V> List<O> |
selectRejected(Iterable<O> beanIterable,
String propertyName,
V... propertyValues)
循环
beanIterable ,获得元素 bean 的 propertyName 属性值都不在
propertyValues 时候的list. |
public static <O> void forEach(Iterable<O> beanIterable, String propertyName, Object propertyValue)
beanIterable
每个元素的每个指定属性 propertyName
的值改成 propertyValue
.
对于以下购物车全选的代码://找到需要处理的对象list List此时你还可以:<ShoppingCartLineCommand>
toDoNeedChangeCheckedCommandList = select( needChangeCheckedCommandList, toggleCheckStatusShoppingCartLinePredicateBuilder.build(shoppingCartLineCommandList, checkStatus)); // 将状态修改成对应状态 for (ShoppingCartLineCommand shoppingCartLineCommand : toDoNeedChangeCheckedCommandList){ shoppingCartLineCommand.setSettlementState(1); }//找到需要处理的对象list List<ShoppingCartLineCommand>
toDoNeedChangeCheckedCommandList = select( needChangeCheckedCommandList, toggleCheckStatusShoppingCartLinePredicateBuilder.build(shoppingCartLineCommandList, checkStatus)); // 将状态修改成对应状态 CollectionsUtil.forEach(toDoNeedChangeCheckedCommandList, "settlementState", 1);
- 如果
beanIterable
是null或者empty,什么都不做- 如果
beanIterable
中有元素是null,将跳过去
O
- the element typebeanIterable
- beanIterablepropertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamepropertyValue
- 指定属性的属性值NullPointerException
- 如果 propertyName
是nullIllegalArgumentException
- 如果 propertyName
是blankIterableUtils.forEach(Iterable, org.apache.commons.collections4.Closure)
,
BeanPropertyValueChangeClosure
public static <O> boolean addAllIgnoreNull(Collection<O> objectCollection, Iterable<? extends O> iterable)
Iterable
元素到指定的objectCollection
,如果 iterable
是null将忽略.
List<String>
list = toList("xinge", "feilong1"); CollectionsUtil.addAllIgnoreNull(list, null); = false
对于以下代码:
private Set可以重构成:<String>
getItemComboIds(List<ShoppingCartLineCommand>
lines){ Set<String>
set = new HashSet<>
(); if (null != lines && lines.size() > 0
){ for (ShoppingCartLineCommand line : lines){ if (line.getComboIds() != null){ set.addAll(line.getComboIds()); } } } return set; }private Set<String>
getItemComboIds(List<ShoppingCartLineCommand>
lines){ if (isNullOrEmpty(lines)){ return Collections.emptySet(); } Set<String>
set = new HashSet<>
(); for (ShoppingCartLineCommand line : lines){ CollectionsUtil.addAllIgnoreNull(set, line.getComboIds()); } return set; }重构之后,方法的复杂度会更小,阅读性更高
O
- the type of object the Collection
containsobjectCollection
- the collection to add to, 不能为nulliterable
- the iterable of elements to addobjectCollection
是否改变,如果改变了,返回true.objectCollection
是null,抛出 NullPointerException
iterable
是null,直接返回falseCollectionUtils.addAll(Collection, Iterable)
CollectionUtils.addIgnoreNull(Collection, Object)
,
CollectionUtils.addAll(Collection, Iterable)
,
CollectionUtils.addAll(Collection, Iterator)
public static <T> boolean addIgnoreNullOrEmpty(Collection<T> objectCollection, T element)
element
元素到指定的objectCollection
,如果 element
是null或者 empty将忽略.
对于以下代码:List可以重构成:<Object[]>
dataList = new ArrayList<>
(); for (T bean : iterable){ Object[] objectArray = toObjectArray(bean, propertyNameList); if (isNotNullOrEmpty(objectArray)){ dataList.add(objectArray); } } return dataList;List重构之后,方法的复杂度会更小,阅读性更高<Object[]>
dataList = new ArrayList<>
(); for (T bean : iterable){ addIgnoreNullOrEmpty(dataList, toObjectArray(bean, propertyNameList)); } return dataList;
T
- the generic typeobjectCollection
- the collection to add to, 不能为nullelement
- element to addobjectCollection
是否改变,如果改变了,返回true.objectCollection
是null,抛出 NullPointerException
element
是null 或者 empty,直接返回falseobjectCollection.add(object)
CollectionUtils.addIgnoreNull(Collection, Object)
public static <O,V> int indexOf(List<O> list, String propertyName, V propertyValue)
list
中,查找第一个属性 propertyName
值是指定值 propertyValue
对象的索引位置.
List<User>
list = new ArrayList<>
(); list.add(new User("张飞", 23)); list.add(new User("关羽", 24)); list.add(new User("刘备", 25)); CollectionsUtil.indexOf(list, "name", "张飞") = 0 CollectionsUtil.indexOf(null, "age", 24) = -1 CollectionsUtil.indexOf(new ArrayList<User>
(), "age", 24) = -1
- 常用于 浏览历史记录,当前的商品id是否在历史记录中第一条位置,如果是,可能就不会操作Cookie,诸如此类的操作
O
- the generic typeV
- the generic typelist
- the listpropertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamepropertyValue
- 指定属性的属性值list
是null 或者 empty,返回 -1propertyName
的值 propertyValue
在 list 查找不到,返回 -1NullPointerException
- 如果 propertyName
是nullIllegalArgumentException
- 如果 propertyName
是blankListUtils.indexOf(List, Predicate)
,
BeanPredicateUtil.equalPredicate(String, Object)
public static <O> List<O> removeAll(Collection<O> objectCollection, Collection<O> removeCollection)
objectCollection
中删除所有的 removeCollection
(原集合对象不变).
- 返回剩余的集合 (原集合对象
objectCollection
不变),如果你不想修改objectCollection
的话,不能直接调用collection.removeAll(remove);
,这个方法非常有用.- 底层实现是调用的
ListUtils.removeAll(Collection, Collection)
,将不是removeElement
的元素加入到新的list返回.
场景: 从list中删除 "feilong2","feilong1"元素
List返回:<String>
list = toList("xinge", "feilong1", "feilong2", "feilong2"); List<String>
removeList = CollectionsUtil.removeAll(list, toList("feilong2", "feilong1"));["xinge"]
O
- the generic typeobjectCollection
- the collection from which items are removed (in the returned collection)removeCollection
- the items to be removed from the returned collection
objectCollection
中排除掉 removeCollection
元素的新的 listNullPointerException
- 如果 objectCollection
是null,或者 removeCollection
是nullListUtils.removeAll(Collection, Collection)
public static <O> List<O> removeAllNull(Collection<O> objectCollection)
objectCollection
中删除所有的 null
元素 (原集合对象不变).
- 返回剩余的集合 (原集合对象
objectCollection
不变),如果你不想修改objectCollection
的话,不能直接调用collection.removeAll(remove);
,这个方法非常有用.- 底层实现是调用的
ListUtils.removeAll(Collection, Collection)
,将不是removeElement
的元素加入到新的list返回.
场景: 从list中删除 null 元素
List返回:<String>
list = toList("xinge", null, "feilong2", null, "feilong2"); List<String>
removeList = CollectionsUtil.removeAllNull(list);"xinge", "feilong2", "feilong2"
O
- the generic typeobjectCollection
- the collection from which items are removed (in the returned collection)objectCollection
中排除掉 null
元素的新的 listNullPointerException
- 如果 objectCollection
是nullListUtils.removeAll(Collection, Collection)
@SafeVarargs public static <O> List<O> remove(Collection<O> objectCollection, O... removeElements)
objectCollection
中 删除removeElements
(原集合对象不变).
- 返回剩余的集合 (原集合对象不变),这个方法非常有用,如果你不想修改
collection
的话,不能调用collection.remove(removeElements);
.- 底层实现是调用的
ListUtils.removeAll(Collection, Collection)
,将不是removeElements
的元素加入到新的list返回.
List返回:<String>
list = new ArrayList<>
(); list.add("xinge"); list.add("feilong1"); list.add("feilong2"); list.add("feilong2"); LOGGER.info(JsonUtil.format(CollectionsUtil.remove(list, "feilong2")));["xinge","feilong1"]此时,原来的list不变:LOGGER.info(JsonUtil.format(list));输出 :["xinge","feilong1","feilong2","feilong2"]
O
- the generic typeobjectCollection
- the object collectionremoveElements
- 需要被删除的元素List
containing all the elements of c
except any elements that also occur in remove
.NullPointerException
- 如果 objectCollection
是nullremoveAll(Collection, Collection)
,
ListUtils.removeAll(Collection, Collection)
public static <O> List<O> removeDuplicate(Collection<O> objectCollection)
List返回:<String>
list = new ArrayList<>
(); list.add("feilong1"); list.add("feilong2"); list.add("feilong2"); list.add("feilong3"); LOGGER.info(JsonUtil.format(CollectionsUtil.removeDuplicate(list)));["feilong1","feilong2","feilong3"]
- 如果原
objectCollection
是有序的,那么返回的结果参照原objectCollection
元素顺序- 原
objectCollection
不变
O
- the generic typeobjectCollection
- the object collectionobjectCollection
是null或者empty,返回 Collections.emptyList()
LinkedHashSet
,再转换成ArrayList
返回LinkedHashSet.LinkedHashSet(Collection)
,
ConvertUtil.toList(Collection)
,
IterableUtils.uniqueIterable(Iterable)
,
http://www.oschina.net/code/snippet_117714_2991?p=2#comments
public static <T,O> List<T> getPropertyValueList(Iterable<O> beanIterable, String propertyName)
beanIterable
,取到对象指定的属性 propertyName
的值,拼成List(ArrayList
).
场景: 获取user list每个元素的id属性值,组成新的list返回
List返回:<User>
list = toList(// new User(2L), new User(5L), new User(5L)); List<Long>
resultList = CollectionsUtil.getPropertyValueList(list, "id"); LOGGER.debug(JsonUtil.format(resultList));[2,5,5]
propertyName
:对于以下的数据结构:
//***************list**************************************** List<UserAddress>
userAddresseList = new ArrayList<>
(); UserAddress userAddress = new UserAddress(); userAddress.setAddress("中南海"); userAddresseList.add(userAddress); //***************map**************************************** Map<String, String>
attrMap = new HashMap<>
(); attrMap.put("蜀国", "赵子龙"); attrMap.put("魏国", "张文远"); attrMap.put("吴国", "甘兴霸"); //--------------------------------------------------------------- UserInfo userInfo1 = new UserInfo(); userInfo1.setAge(28); User user1 = new User(2L); user1.setLoves(new String[] { "sanguo1", "xiaoshuo1" }); user1.setUserInfo(userInfo1); user1.setAttrMap(attrMap); user1.setUserAddresseList(userAddresseList); //--------------------------------------------------------------- UserInfo userInfo2 = new UserInfo(); userInfo2.setAge(null); User user2 = new User(3L); user2.setLoves(new String[] { "sanguo2", "xiaoshuo2" }); user2.setUserInfo(userInfo2); user2.setAttrMap(attrMap); user2.setUserAddresseList(userAddresseList); List<User>
userList = toList(user1,user2);以下情况:
//数组,取userList 每个元素的 loves属性第2个元素的值 CollectionsUtil.getPropertyValueList(userList, "loves[1]") = ["xiaoshuo1","xiaoshuo2"] //级联对象,取userList 每个元素的 userInfo属性的 age 属性的值 CollectionsUtil.getPropertyValueList(userList, "userInfo.age") = [28,null] //Map,取userList 每个元素的 attrMap属性中的key是 "蜀国" 的值 CollectionsUtil.getPropertyValueList(userList, "attrMap(蜀国)") = ["赵子龙","赵子龙"] //集合,取userList 每个元素的 userAddresseList属性中的第一个元素 CollectionsUtil.getPropertyValueList(userList, "userAddresseList[0]") = [{"address": "中南海"},{"address": "中南海"}]
支持以下类型:
- bean Iterable
- 诸如List
<User>
,Set<User>
等- map Iterable
- 比如
List<Map<String, String>>
示例:List<Map<String, String>>
list = newArrayList(); list.add(toMap("key", "value1")); list.add(toMap("key", "value2")); list.add(toMap("key", "value3")); List<String>
resultList = CollectionsUtil.getPropertyValueList(list, "(key)"); assertThat(resultList, contains("value1", "value2", "value3"));- list Iterable
- 比如
List<List<String>>
示例:List<List<String>>
list = newArrayList(); list.add(toList("小明", "18")); list.add(toList("小宏", "18")); list.add(toList("小振", "18")); List<String>
resultList = CollectionsUtil.getPropertyValueList(list, "[0]"); assertThat(resultList, contains("小明", "小宏", "小振"));- 数组 Iterable
- 比如
List<String[]>
示例:List<String[]>
list = newArrayList(); list.add(toArray("三国", "水浒")); list.add(toArray("西游", "金瓶梅")); List<String>
resultList = CollectionsUtil.getPropertyValueList(list, "[0]"); assertThat(resultList, contains("三国", "西游"));
T
- 返回集合类型 generic typeO
- 可迭代对象类型 generic typebeanIterable
- 支持
<User>
,Set<User>
等List<Map<String, String>>
List<List<String>>
List<String[]>
propertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamebeanIterable
是null或者empty,会返回empty ArrayListpropertyName
是null,抛出 NullPointerException
propertyName
是blank,抛出 IllegalArgumentException
PropertyValueObtainer.getPropertyValueCollection(Iterable, String, Collection)
public static <T,O> Set<T> getPropertyValueSet(Iterable<O> beanIterable, String propertyName)
beanIterable
,取到对象指定的属性 propertyName
的值,拼成Set
(LinkedHashSet
).
- 返回的是
LinkedHashSet
,顺序是参数beanIterable
元素的顺序
List返回:<User>
list = new ArrayList<>
(); list.add(new User(2L)); list.add(new User(5L)); list.add(new User(5L)); LOGGER.info(JsonUtil.format(CollectionsUtil.getPropertyValueSet(list, "id")));[2,5]
T
- the generic typeO
- the generic typebeanIterable
- 支持
<User>
,Set<User>
等List<Map<String, String>>
List<List<String>>
List<String[]>
propertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamebeanIterable
是null或者empty,会返回empty LinkedHashSet
propertyName
是null,抛出 NullPointerException
propertyName
是blank,抛出 IllegalArgumentException
PropertyValueObtainer.getPropertyValueCollection(Iterable, String, Collection)
public static <K,V,O> Map<K,V> getPropertyValueMap(Iterable<O> beanIterable, String keyPropertyName, String valuePropertyName)
beanIterable
,以 keyPropertyName
属性值为key, valuePropertyName
属性值为value,组成map返回.
- 返回的是
LinkedHashMap
,顺序是参数beanIterable
元素的顺序- 如果有元素
keyPropertyName
属性值相同,那么后面的值会覆盖前面的值
List返回:<User>
list = new ArrayList<>
(); list.add(new User("张飞", 23)); list.add(new User("关羽", 24)); list.add(new User("刘备", 25)); LOGGER.info(JsonUtil.format(CollectionsUtil.getPropertyValueMap(list, "name", "age")));{ "张飞": 23, "关羽": 24, "刘备": 25 }
如果有元素
keyPropertyName
属性值相同,那么后面的值会覆盖前面的值List返回:<User>
list = new ArrayList<>
(); list.add(new User("张飞", 23)); list.add(new User("关羽", 24)); list.add(new User("张飞", 25)); LOGGER.info(JsonUtil.format(CollectionsUtil.getPropertyValueMap(list, "name", "age")));{ "张飞": 25, "关羽": 24, }
K
- the key typeV
- the value typeO
- 可迭代对象类型 generic typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等keyPropertyName
- 泛型O对象指定的属性名称,取到的值将作为返回的map的key,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamevaluePropertyName
- 泛型O对象指定的属性名称,取到的值将作为返回的map的value,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamebeanIterable
是null或者empty,返回 Collections.emptyMap()
keyPropertyName
是null,抛出 NullPointerException
keyPropertyName
是blank,抛出 IllegalArgumentException
valuePropertyName
是null,抛出 NullPointerException
valuePropertyName
是blank,抛出 IllegalArgumentException
PropertyUtil.getProperty(Object, String)
public static <O,V> O find(Iterable<O> beanIterable, String propertyName, V propertyValue)
iterable
中,第一个 propertyName
属性名称值是 propertyValue
的对应元素.
场景: 从list中查找name是 关羽 的User对象
List返回:<User>
list = new ArrayList<>
(); list.add(new User("张飞", 23)); list.add(new User("关羽", 24)); list.add(new User("刘备", 25)); list.add(new User("关羽", 50)); LOGGER.info(JsonUtil.format(CollectionsUtil.find(list, "name", "关羽")));{ "age": 24, "name": "关羽" }
- 返回第一个匹配对象
O
- the generic typeV
- the value typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等propertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamepropertyValue
- 指定的值iterable
是null, 返回nullpropertyName
是null,抛出 NullPointerException
propertyName
是blank,抛出 IllegalArgumentException
iterable
中没有相关元素的属性propertyName
值是propertyValue
,返回nullfind(Iterable, Predicate)
,
BeanPredicateUtil.equalPredicate(String, Object)
public static <O> O find(Iterable<O> iterable, Predicate<O> predicate)
predicate
的第一个元素并返回.
场景: 从list中查找name是 关羽,并且 age等于30的User对象
List返回:<User>
list = toList(// new User("张飞", 23), new User("关羽", 24), new User("刘备", 25), new User("关羽", 30)); Map<String, Object>
map = new HashMap<>
(); map.put("name", "关羽"); map.put("age", 30); Predicate<User>
predicate = BeanPredicateUtil.equalPredicate(map); User user = CollectionsUtil.find(list, predicate); LOGGER.debug(JsonUtil.format(user));{ "age": 30, "name": "关羽" }
- 返回第一个匹配对象
O
- the generic typeiterable
- the iterable to search, may be nullpredicate
- the predicate to use, may not be nullpredicate
是 null,将抛出NullPointerException
iterable
是null, 返回nulliterable
中没有相关元素匹配 predicate
,返回nullIterableUtils.find(Iterable, Predicate)
@SafeVarargs public static <O,V> List<O> select(Iterable<O> beanIterable, String propertyName, V... propertyValues)
beanIterable
,获得元素 bean
的 propertyName
的值,判断是否在propertyValues
数组中;如果在,将该对象存入list中返回.
查询的结果的顺序按照原来
beanIterable
里面的顺序,和参数propertyValues
无关,如果你需要结果里面的元素按照指定的propertyValues
顺序排序的话,可以将结果再调用SortUtil.sortListByFixedOrderPropertyValueArray(List, String, Object...)
List返回:<User>
list = new ArrayList<>
(); list.add(new User("张飞", 23)); list.add(new User("关羽", 24)); list.add(new User("刘备", 25)); String[] array = { "刘备", "关羽" }; LOGGER.info(JsonUtil.format(CollectionsUtil.select(list, "name", array)));[{ "age": 24, "name": "关羽" },{ "age": 25, "name": "刘备" }]
O
- the generic typeV
- the value typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等propertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamepropertyValues
- the valuesbeanIterable
是null或者empty,返回 Collections.emptyList()
propertyName
是null,抛出 NullPointerException
propertyName
是blank,抛出 IllegalArgumentException
propertyValues
是null,返回 new ArrayList<O>
BeanPredicateUtil.containsPredicate(String, Object...)
public static <O,V> List<O> select(Iterable<O> beanIterable, String propertyName, Collection<V> propertyValueList)
beanIterable
,获得元素 bean
的propertyName
的值,判断是否在propertyValueList
集合中;如果在,将该对象存入list中返回.
- 查询的结果的顺序按照原来
beanIterable
里面的顺序,和参数propertyValueList
无关,如果你需要结果里面的元素按照指定的propertyValueList
顺序排序的话,可以将结果再调用SortUtil.sortListByFixedOrderPropertyValueList(List, String, List)
- 和该方法正好相反的是
selectRejected(Iterable, String, Collection)
场景: 查询 name属性是"张飞"或者是"刘备"的 User list
List返回:<User>
list = new ArrayList<>
(); list.add(new User("张飞", 23)); list.add(new User("关羽", 24)); list.add(new User("刘备", 25)); List<String>
propertyValueList = new ArrayList<>
(); propertyValueList.add("张飞"); propertyValueList.add("刘备"); LOGGER.info(JsonUtil.format(CollectionsUtil.select(list, "name", propertyValueList)));[{ "age": 23, "name": "张飞" },{ "age": 25, "name": "刘备" }]
对于以下代码:
// 当前店铺 的物流方式Id set Set可以重构成:<Long>
distributionModeIdSet = new HashSet<>
(); for (TemeplateDistributionMode tdCmd : temeplateDistributionModeList){ distributionModeIdSet.add(tdCmd.getDistributionModeId()); } // 拿到所有的物流方式 列表 List<DistributionCommand>
distributionCommandList = freigthMemoryManager.getDistributionList(); // 根据 物流方式ID 找出 支持本商铺的 DistributionCommand List<DistributionCommand>
curShopDistributionCommandList = new ArrayList<>
(); for (Long modeId : distributionModeIdSet){ for (DistributionCommand distributionCmd : distributionCommandList){ if (modeId.equals(distributionCmd.getDistributionModeId())){ curShopDistributionCommandList.add(distributionCmd); } } }// 当前店铺 的物流方式Id set Set<Long>
distributionModeIdSet = CollectionsUtil.getPropertyValueSet(temeplateDistributionModeList, "distributionModeId"); // 拿到所有的物流方式 列表 List<DistributionCommand>
distributionCommandList = freigthMemoryManager.getDistributionList(); // 根据 物流方式ID 找出 支持本商铺的 DistributionCommand List<DistributionCommand>
curShopDistributionCommandList = CollectionsUtil.select(distributionCommandList, "distributionModeId", distributionModeIdSet);
O
- the generic typeV
- the value typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等propertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamepropertyValueList
- the valuesbeanIterable
是null或者empty,返回 Collections.emptyList()
propertyName
是null,抛出 NullPointerException
propertyName
是blank,抛出 IllegalArgumentException
select(Iterable, Predicate)
select(Iterable, Predicate)
,
BeanPredicateUtil.containsPredicate(String, Collection)
public static <O> List<O> select(Iterable<O> beanIterable, Predicate<O> predicate)
Predicate
,返回查询出来的集合.
- 和该方法正好相反的是
selectRejected(Iterable, Predicate)
场景: 查找等于 1的元素
List返回:<Long>
list = new ArrayList<>
(); list.add(1L); list.add(1L); list.add(2L); list.add(3L); LOGGER.info(JsonUtil.format(CollectionsUtil.select(list, new EqualPredicate<Long>
(1L))));[1,1]
场景: 查找大于 10的元素
Comparator返回:<Integer>
comparator = ComparatorUtils.naturalComparator(); Predicate<Integer>
predicate = new ComparatorPredicate<Integer>
(10, comparator, Criterion.LESS); List<Integer>
select = CollectionsUtil.select(toList(1, 5, 10, 30, 55, 88, 1, 12, 3), predicate); LOGGER.debug(JsonUtil.format(select, 0, 0));[30,55,88,12]
O
- the generic typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等predicate
- 接口封装了对输入对象的判断,返回true或者false,可用的实现类有
beanIterable
是null或者empty,返回 Collections.emptyList()
CollectionUtils.select(Iterable, Predicate)
CollectionUtils.select(Iterable, Predicate)
@SafeVarargs public static <O,V> List<O> selectRejected(Iterable<O> beanIterable, String propertyName, V... propertyValues)
beanIterable
,获得元素 bean
的 propertyName
属性值都不在
propertyValues
时候的list.
场景: 查询name 不是刘备 也不是张飞的 User list元素
List返回:<User>
list = new ArrayList<>
(); list.add(new User("张飞", 23)); list.add(new User("关羽", 24)); list.add(new User("刘备", 25)); List<User>
selectRejected = CollectionsUtil.selectRejected(list, "name", "刘备", "张飞"); LOGGER.info(JsonUtil.format(selectRejected));[{ "age": 24, "name": "关羽" }]
O
- the generic typeV
- the value typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等propertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamepropertyValues
- the valuesbeanIterable
是null或者empty,返回 Collections.emptyList()
propertyName
是null,抛出 NullPointerException
propertyName
是blank,抛出 IllegalArgumentException
BeanPredicateUtil.containsPredicate(String, Object...)
,
selectRejected(Iterable, Predicate)
public static <O,V> List<O> selectRejected(Iterable<O> beanIterable, String propertyName, Collection<V> propertyValueList)
beanIterable
,获得元素 bean
的 propertyName
的值,判断是否不在propertyValueList
集合中;如果不在,将该对象存入list中返回.
场景: 查询 name属性是不是"张飞",也不是"刘备"的 User list
List返回:<User>
list = new ArrayList<>
(); list.add(new User("张飞", 23)); list.add(new User("关羽", 24)); list.add(new User("刘备", 25)); List<String>
propertyValueList = new ArrayList<>
(); propertyValueList.add("张飞"); propertyValueList.add("刘备"); LOGGER.info(JsonUtil.format(CollectionsUtil.selectRejected(list, "name", propertyValueList)));[{ "age": 24, "name": "关羽" }]
- 和该方法正好相反的是
select(Iterable, String, Collection)
O
- the generic typeV
- the value typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等propertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamepropertyValueList
- the valuesbeanIterable
是null或者empty,返回 Collections.emptyList()
propertyName
是null,抛出 NullPointerException
propertyName
是blank,抛出 IllegalArgumentException
BeanPredicateUtil.containsPredicate(String, Collection)
,
selectRejected(Iterable, Predicate)
public static <O> List<O> selectRejected(Iterable<O> beanIterable, Predicate<O> predicate)
beanIterable
,获得元素 bean
,判断是否不匹配predicate
,如果不匹配
,将该对象存入list中返回.
- 和该方法正好相反的是
select(Iterable, Predicate)
场景: 从list中查找不等于1的元素
List返回:<Long>
list = toList(1L, 1L, 2L, 3L); CollectionsUtil.selectRejected(list, new EqualPredicate<Long>
(1L))2L, 3L
O
- the generic typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等predicate
- the predicatebeanIterable
是null或者empty,返回 Collections.emptyMap()
CollectionUtils.selectRejected(Iterable, Predicate)
public static <O,T> List<T> collect(Iterable<O> inputIterable, Transformer<? super O,? extends T> transformer)
inputIterable
,将每个元素使用 transformer
转换成新的对象,返回新的list.
List返回:<String>
list = new ArrayList<>
(); list.add("xinge"); list.add("feilong1"); list.add("feilong2"); list.add("feilong2"); Transformer<String, Object>
nullTransformer = TransformerUtils.nullTransformer(); List<Object>
collect = CollectionsUtil.collect(list, nullTransformer); LOGGER.info(JsonUtil.format(collect, 0, 0));[null,null,null,null]
比如购物车功能,有游客购物车CookieShoppingCartLine以及内存购物车对象 ShoppingCartLineCommand,两个数据结构部分元素相同,
用户登陆需要把cookie中的购物车转成内存购物车ShoppingCartLineCommand list,这时我们可以先创建ToShoppingCartLineCommandTransformer代码示例:
class ToShoppingCartLineCommandTransformer implements Transformer<CookieShoppingCartLine, ShoppingCartLineCommand>
{ private static final String[] COPY_PROPERTY_NAMES = {"skuId","extentionCode","quantity","createTime","settlementState","lineGroup" }; public ShoppingCartLineCommand transform(CookieShoppingCartLine cookieShoppingCartLine){ // 将cookie中的购物车 转换为 shoppingCartLineCommand ShoppingCartLineCommand shoppingLineCommand = new ShoppingCartLineCommand(); PropertyUtil.copyProperties(shoppingLineCommand, cookieShoppingCartLine, COPY_PROPERTY_NAMES); shoppingLineCommand.setId(cookieShoppingCartLine.getId()); shoppingLineCommand.setGift(null == cookieShoppingCartLine.getIsGift() ? false : cookieShoppingCartLine.getIsGift()); return shoppingLineCommand; } }然后调用:
public List<ShoppingCartLineCommand>
load(HttpServletRequest request){ // 获取cookie中的购物车行集合 List<CookieShoppingCartLine>
cookieShoppingCartLineList = getCookieShoppingCartLines(request); if (isNullOrEmpty(cookieShoppingCartLineList)){ return null; } return CollectionsUtil.collect(cookieShoppingCartLineList, new ToShoppingCartLineCommandTransformer()); }
O
- the type of object in the input collectionT
- the type of object in the output collectioninputIterable
- the inputIterable to get the input fromtransformer
- the transformer to use, may be nullinputIterable
是null,返回 nulltransformer
是null,返回 empty listCollectionUtils.collect(Iterable, Transformer)
,
CollectionUtils.transform(Collection, Transformer)
public static <O,I> List<O> collect(Iterable<I> inputBeanIterable, Class<O> outputListBeanType, String... includePropertyNames)
inputBeanIterable
,将每个元素使用转换程成新的 outputListBeanType 类型对象(如有需要只copy传入的includePropertyNames
属性)
返回新的list.
已知有以下两个类 User 和 Customerpublic class User{ // The id. private Long id = 0L; //** The name. private String name = "feilong"; //** 年龄. private Integer age; //setter /getter public User(Long id, String name){ this.id = id; this.name = name; } }public class Customer{ //** The id. private long id; //* The name. private String name; //setter /getter }此时有以下的 List<User>
需要转换成List<Customer>
List以前你需要如此这般写:<User>
list = toList(// new User(23L, "张飞"), new User(24L, "关羽"), new User(25L, "刘备"));List<Customer>
customerList = new ArrayList<>
(); for (User user : list){ Customer customer = new Customer(); customer.setId(user.getId()); customer.setName(user.getName()); customerList.add(customer); }如果属性很多,书写代码很繁琐
此时你可以这么写:
List<Customer>
customerList = CollectionsUtil.collect(list, Customer.class);一行代码搞定集合转换问题
如果你只想转换id属性,你可以:
List<Customer>
customerList = CollectionsUtil.collect(list, Customer.class,"id");
- outputListBeanType 需要有默认的构造函数
O
- the generic typeI
- the generic typeinputBeanIterable
- 输入的input bean IterableoutputListBeanType
- 要转成Bean list的类型.includePropertyNames
- 包含的属性数组名字数组,(can be nested/indexed/mapped/combo),includePropertyNames
,含有 inputBeanIterable
bean 没有的属性名字,将会抛出异常includePropertyNames
,含有 inputBeanIterable
bean有,但是outputListBeanType
没有的属性名字,会抛出异常,seecopyProperties
Line2078inputBeanIterable
是null,返回 nullinputBeanIterable
中有元素是null,那么返回的list对应位置的元素也是nulloutputListBeanType
是null,抛出 NullPointerException
public static <O,T> List<T> collect(Iterator<O> inputIterator, Transformer<? super O,? extends T> transformer)
inputIterator
,将每个元素使用 transformer
转换成新的对象 返回新的list.
场景: 一个简单的将list中的所有元素转成null
List返回:<String>
list = toList("xinge", "feilong1", "feilong2", "feilong2"); Transformer<String, Object>
nullTransformer = TransformerUtils.nullTransformer(); List<Object>
collect = CollectionsUtil.collect(list.iterator(), nullTransformer); LOGGER.info(JsonUtil.format(collect, 0, 0));[null,null,null,null]
O
- the type of object in the output collectionT
- the type of object in the input collectioninputIterator
- the iterator to get the input fromtransformer
- the transformer to use, may be nullinputIterator
是null,返回 nulltransformer
是null,返回 new ArrayList<>
CollectionUtils.collect(java.util.Iterator, Transformer)
public static <T,O> Map<T,List<O>> group(Iterable<O> beanIterable, String propertyName)
beanIterable
,以 元素的 propertyName
属性值为key,相同值的元素组成list作为value,封装成map返回.
- 返回的
LinkedHashMap
,key是beanIterable
中的元素对象中propertyName
的值,value是beanIterable
中的元素对象;- 顺序是
beanIterable
propertyName
的值顺序,如果需要排序,可自行调用SortUtil.sortMapByKeyAsc(Map)
,SortUtil.sortMapByKeyDesc(Map)
,SortUtil.sortMapByValueAsc(Map)
,SortUtil.sortMapByValueDesc(Map)
或者,SortUtil.sortMap(Map, java.util.Comparator)
- 属性
propertyName
值相同的元素,组成集合 list- 如果value只需要单值的话,可以调用
groupOne(Iterable, String)
方法
List返回:<User>
list = toList( new User("张飞", 23), new User("刘备", 25), new User("刘备", 30)); Map<String, List<User>>
map = CollectionsUtil.group(list, "name"); LOGGER.debug(JsonUtil.format(map));{ "张飞": [ { "age": 23, "name": "张飞", }], "刘备": [ { "age": 25, "name": "刘备", }, { "age": 30, "name": "刘备", } ] }
T
- 注意,此处的T是属性值,Object类型,如果从excel中读取的类型是String,那么不能简简单单的使用Integer来接收,不能强制转换O
- the generic typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等propertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamebeanIterable
是null或者empty,返回 Collections.emptyMap()
propertyName
是null,抛出 NullPointerException
propertyName
是blank,抛出 IllegalArgumentException
group(Iterable, String, Predicate)
public static <T,O> Map<T,List<O>> group(Iterable<O> beanIterable, String propertyName, Predicate<O> includePredicate)
beanIterable
,找到符合条件的 includePredicate
的元素,以元素的 propertyName
属性值为key,相同值的元素组成list作为value,封装成map返回.
- 返回的
LinkedHashMap
,key是beanIterable
中的元素对象中propertyName
的值,value是beanIterable
中的元素对象;- 顺序是
beanIterable
propertyName
的值顺序,如果需要排序,可自行调用SortUtil.sortMapByKeyAsc(Map)
,SortUtil.sortMapByKeyDesc(Map)
,SortUtil.sortMapByValueAsc(Map)
,SortUtil.sortMapByValueDesc(Map)
或者,SortUtil.sortMap(Map, java.util.Comparator)
场景: 将age
>
20的User,按照name 进行 groupList返回:<User>
list = new ArrayList<>
(); list.add(new User("张飞", 10)); list.add(new User("张飞", 28)); list.add(new User("刘备", 32)); list.add(new User("刘备", 30)); list.add(new User("刘备", 10)); Map<String, List<User>>
map = CollectionsUtil.group(list, "name", new Predicate<User>
(){@Override
public boolean evaluate(User user){ return user.getAge()>
20; } }); LOGGER.info(JsonUtil.format(map));{ "张飞": [{ "age": 28, "name": "张飞" }], "刘备": [{ "age": 32, "name": "刘备" },{ "age": 30, "name": "刘备" } ] }当然,对于上述代码,你还可以优化成:
Predicate参见<User>
comparatorPredicate = BeanPredicateUtil.comparatorPredicate("age", 20, Criterion.LESS); Map<String, List<User>>
map = CollectionsUtil.group(list, "name", comparatorPredicate);BeanPredicateUtil.comparatorPredicate(String, Comparable, org.apache.commons.collections4.functors.ComparatorPredicate.Criterion)
T
- 注意,此处的T是属性值,Object类型,如果从excel中读取的类型是String,那么不能简简单单的使用Integer来接收,不能强制转换O
- the generic typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等propertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNameincludePredicate
- the include predicatebeanIterable
是null或者empty,返回 Collections.emptyMap()
propertyName
是null,抛出 NullPointerException
propertyName
是blank,抛出 IllegalArgumentException
includePredicate
,返回 empty LinkedHashMap
includePredicate
是null,那么以所有的元素进行分组PropertyUtil.getProperty(Object, String)
,
groupOne(Iterable, String)
public static <T,O> Map<T,List<O>> group(Iterable<O> beanIterable, Transformer<O,T> keyTransformer)
beanIterable
,将元素使用keyTransformer
转成key,相同值的元素组成list作为value,封装成map返回.
- 返回的
LinkedHashMap
,key是beanIterable
中的元素 使用keyTransformer
转换的值,value是beanIterable
中的元素对象(相同key值,组成list);- 返回的
LinkedHashMap
顺序,是beanIterable
元素顺序,如果需要排序,可自行调用SortUtil.sortMapByKeyAsc(Map)
,SortUtil.sortMapByKeyDesc(Map)
,SortUtil.sortMapByValueAsc(Map)
,SortUtil.sortMapByValueDesc(Map)
或者,SortUtil.sortMap(Map, java.util.Comparator)
场景: 从user list中,提取user的姓名的姓为key,user组成list,返回map
User mateng55 = new User("马腾", 55); User machao28 = new User("马超", 28); User madai27 = new User("马岱", 27); User maxiu25 = new User("马休", 25); User zhangfei28 = new User("张飞", 28); User liubei32 = new User("刘备", 32); User guanyu50 = new User("关羽", 50); User guanping32 = new User("关平", 32); User guansuo31 = new User("关索", 31); User guanxing20 = new User("关兴", 18); //--------------------------------------------------------------- List返回:<User>
list = toList(mateng55, machao28, madai27, maxiu25, zhangfei28, liubei32, guanyu50, guanping32, guansuo31, guanxing20); //--------------------------------------------------------------- Map<String, List<User>>
map = CollectionsUtil.group(list,new Transformer<User, String>
(){ @Override public String transform(User user){ //提取名字 的姓 return user.getName().substring(0, 1); } }); LOGGER.debug(JsonUtil.format(map));{ "马":[{ "age": 55, "name": "马腾", },{ "age": 28, "name": "马超", },{ "age": 27, "name": "马岱", },{ "age": 25, "name": "马休", } ], "张": [{ "age": 28, "name": "张飞", }], "刘": [{ "age": 32, "name": "刘备", }], "关": [{ "age": 50, "name": "关羽", },{ "age": 32, "name": "关平", },{ "age": 31, "name": "关索", },{ "age": 18, "name": "关兴", } ] }
T
- the generic typeO
- the generic typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等keyTransformer
- 返回的map,key转换器beanIterable
是null或者empty,返回 Collections.emptyMap()
keyTransformer
是null,抛出 NullPointerException
public static <T,O> Map<T,List<O>> group(Iterable<O> beanIterable, Predicate<O> includePredicate, Transformer<O,T> keyTransformer)
beanIterable
,找到符合条件的 includePredicate
的元素,将元素使用keyTransformer
转成key
,相同值的元素组成list作为value,封装成map返回.
- 返回的
LinkedHashMap
,key是beanIterable
中的元素 使用keyTransformer
转换的值,value是beanIterable
中的元素对象(相同key值,组成list);- 返回的
LinkedHashMap
顺序,是beanIterable
元素顺序,如果需要排序,可自行调用SortUtil.sortMapByKeyAsc(Map)
,SortUtil.sortMapByKeyDesc(Map)
,SortUtil.sortMapByValueAsc(Map)
,SortUtil.sortMapByValueDesc(Map)
或者,SortUtil.sortMap(Map, java.util.Comparator)
场景: 从user list中,提取 年龄 大于20的user,user的姓名的姓为key,user组成list,返回map
User mateng55 = new User("马腾", 55); User machao28 = new User("马超", 28); User madai27 = new User("马岱", 27); User maxiu25 = new User("马休", 25); User zhangfei28 = new User("张飞", 28); User liubei32 = new User("刘备", 32); User guanyu50 = new User("关羽", 50); User guanping32 = new User("关平", 32); User guansuo31 = new User("关索", 31); User guanxing20 = new User("关兴", 18); //--------------------------------------------------------------- List返回:<User>
list = toList(mateng55, machao28, madai27, maxiu25, zhangfei28, liubei32, guanyu50, guanping32, guansuo31, guanxing20); //--------------------------------------------------------------- Predicate<User>
comparatorPredicate = BeanPredicateUtil.comparatorPredicate("age", 20, Criterion.LESS); Map<String, List<User>>
map = CollectionsUtil.group(list, comparatorPredicate, new Transformer<User, String>
(){ @Override public String transform(User user){ //提取名字 的姓 return user.getName().substring(0, 1); } }); LOGGER.debug(JsonUtil.format(map));{ "马":[{ "age": 55, "name": "马腾", },{ "age": 28, "name": "马超", },{ "age": 27, "name": "马岱", },{ "age": 25, "name": "马休" }], "张": [{ "age": 28, "name": "张飞" }], "刘": [{ "age": 32, "name": "刘备" }], "关": [{ "age": 50, "name": "关羽" },{ "age": 32, "name": "关平" },{ "age": 31, "name": "关索" }] }
T
- the generic typeO
- the generic typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等includePredicate
- the include predicatekeyTransformer
- 返回的map,key转换器beanIterable
是null或者empty,返回 Collections.emptyMap()
keyTransformer
是null,抛出 NullPointerException
includePredicate
是null,那么以所有的元素进行分组includePredicate
,返回 empty LinkedHashMap
Transformer.transform(Object)
,
List to Map 实现类似矩阵的逻辑 by ananbeikepublic static <T,O> Map<T,O> groupOne(Iterable<O> beanIterable, String propertyName)
iterable
,以元素的 propertyName
属性值为key,元素为value,封装成map返回(map只put第一个匹配的元素,后面出现相同的元素将会忽略).
- 返回的
LinkedHashMap
,key是iterable
中的元素对象中propertyName
的值,value是beanIterable
中的元素对象;- 顺序是
beanIterable
propertyName
的值 顺序,如果需要排序,可自行调用SortUtil.sortMapByKeyAsc(Map)
,SortUtil.sortMapByKeyDesc(Map)
,SortUtil.sortMapByValueAsc(Map)
,SortUtil.sortMapByValueDesc(Map)
或者,SortUtil.sortMap(Map, java.util.Comparator)
- 间接的可以做到基于某个属性值去重的效果
- 如果value需要是集合的话,可以调用
group(Iterable, String)
方法
List返回:<User>
list = new ArrayList<>
(); list.add(new User("张飞", 23)); list.add(new User("刘备", 25)); list.add(new User("刘备", 30)); Map<String, User>
map = CollectionsUtil.groupOne(list, "name"); LOGGER.info(JsonUtil.format(map));{ "张飞": { "age": 23, "name": "张飞" }, "刘备": { "age": 25, "name": "刘备" } }
T
- the generic typeO
- the generic typebeanIterable
- bean Iterable,诸如List<User>
,Set<User>
等propertyName
- 泛型O对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
propertyNamebeanIterable
是null或者empty,返回 Collections.emptyMap()
propertyName
是null,抛出 NullPointerException
propertyName
是blank,抛出 IllegalArgumentException
group(Iterable, String)
public static <E> ArrayList<E> newArrayList()
ArrayList
instance .E
- the element typepublic static <E> LinkedList<E> newLinkedList()
LinkedList
instance .E
- the element typepublic static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList()
CopyOnWriteArrayList
instance .E
- the element typeCopyOnWriteArrayList
public static <E> HashSet<E> newHashSet()
newHashSet
instance .E
- the element typepublic static <E> LinkedHashSet<E> newLinkedHashSet()
LinkedHashSet
instance .E
- the element typeLinkedHashSet
Copyright © 2008-2019 by feilong