java8的lambda表达式提供了一些方便list操作的方法,主要涵盖分组、过滤、求和、最值、排序、去重。跟之前的传统写法对比,能少写不少代码。
新建实体类
package ;
import ;
import ;
public class User {
private Long id;
//姓名
private String name;
//年龄
private int age;
//工号
private String jobNumber;
//性别
private String sex;
//入职日期
private Date entryDate;
//家庭成员数量
private BigDecimal familyMemberQuantity;
public Long getId() {
return id;
}
public void setId(Long id) {
= id;
}
public String getName() {
return name;
}
public void setName(String name) {
= name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
= age;
}
public String getJobNumber() {
return jobNumber;
}
public void setJobNumber(String jobNumber) {
= jobNumber;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
= sex;
}
public Date getEntryDate() {
return entryDate;
}
public void setEntryDate(Date entryDate) {
= entryDate;
}
public BigDecimal getFamilyMemberQuantity() {
return familyMemberQuantity;
}
public void setFamilyMemberQuantity(BigDecimal familyMemberQuantity) {
= familyMemberQuantity;
}
}
1.分组
通过groupingBy可以分组指定字段
//分组
Map<String, List<User>> groupBySex = ().collect((User::getSex));
//遍历分组
for (<String, List<User>> entryUser : ()) {
String key = ();
List<User> entryUserList = ();
}
上门的分组存在key空值安全问题,需要做过滤或封装处理
用Optional封装使用中会报No value present
//分组添加累计
Map<Optional<Long>, List<SalesOrderMonthlyStatementVo>> groupMap = ().collect((x -> (())));
//遍历分组
for (<Optional<Long>, List<SalesOrderMonthlyStatementVo>> entryGroup : ()) {
Optional<Long> key = ();
Long groupId = ();
List<SalesOrderMonthlyStatementVo> entryGroupList = ();
}
正确使用方法如下,自定义groupingBy_WithNullKeys
/** Like , but accepts null keys. */
public static <T, A> Collector<T, ?, Map<A, List<T>>>
groupingBy_WithNullKeys(Function<? super T, ? extends A> classifier) {
return (
classifier,
Collections::singletonList,
(List<T> oldList, List<T> newEl) -> {
List<T> newList = new ArrayList<>(() + 1);
(oldList);
(newEl);
return newList;
});
}
然后调用
Map<Long, List<SalesOrderMonthlyStatementVo>> groupMap = ().collect(groupingBy_WithNullKeys(x -> ()));
多字段分组
Function<WarehouseReceiptLineBatch, List<Object>> compositeKey = wlb ->
Arrays.<Object>asList((), (), ());
Map<Object, List<WarehouseReceiptLineBatch>> map =
().collect((compositeKey, ()));
//遍历分组
for (<Object, List<WarehouseReceiptLineBatch>> entryUser : ()) {
List<Object> key = (List<Object>) ();
List<WarehouseReceiptLineBatch> entryUserList = ();
Long warehouseReceiptLineId = (Long) (0);
Long warehouseAreaId = (Long) (1);
Long warehouseLocationId = (Long) (2);
}
2.过滤
通过filter方法可以过滤某些条件
//过滤
//排除掉工号为201901的用户
List<User> userCommonList = ().filter(a -> !().equals("201901")).collect(());
3.求和
分基本类型和大数类型求和,基本类型先mapToInt,然后调用sum方法,大数类型使用reduce调用BigDecimal::add方法
//求和
//基本类型
int sumAge = ().mapToInt(User::getAge).sum();
//BigDecimal求和
BigDecimal totalQuantity = ().map(User::getFamilyMemberQuantity).reduce(, BigDecimal::add);
上面的求和不能过滤bigDecimal对象为null的情况,可能会报空指针,这种情况,我们可以用filter方法过滤,或者重写求和方法
重写求和方法
package ;
import ;
public class BigDecimalUtils {
public static BigDecimal ifNullSet0(BigDecimal in) {
if (in != null) {
return in;
}
return ;
}
public static BigDecimal sum(BigDecimal ...in){
BigDecimal result = ;
for (int i = 0; i < ; i++){
result = (ifNullSet0(in[i]));
}
return result;
}
}
使用重写的方法
BigDecimal totalQuantity2 = ().map(User::getFamilyMemberQuantity).reduce(, BigDecimalUtils::sum);
判断对象空
(x -> x!=null)
(Objects::nonNull)
判断字段空
(x -> ()!=null)
4.最值
求最小与最大,使用min max方法
//最小
Date minEntryDate = ().map(User::getEntryDate).min(Date::compareTo).get();
//最大
Date maxEntryDate = ().map(User::getEntryDate).max(Date::compareTo).get();
有时候我们需要知道最大最小对应的这个对象,我们可以通过如下方法获取
Comparator<LeasingBusinessContract> comparator = (LeasingBusinessContract::getLeaseEndDate);
LeasingBusinessContract maxObject = ().max(comparator).get();
转map
/**
* List -> Map
* 需要注意的是:
* toMap 如果集合对象有重复的key,会报错Duplicate key ....
* user1,user2的id都为1。
* 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
*/
Map<Long, User> userMap = ().collect((User::getId, a -> a,(k1,k2)->k1));
list转map的时候有时候会将date类型作为key,实际情况中使用string的多,我们可以将某个字段转成string
Map<String, WorkCenterLoadVo> workCenterMap = ().collect((key->((), "yyyy-MM-dd"), a -> a,(k1,k2)->k1));
list转map有时候会用到多字段key的map结构,除了常用的key用字符串连接,也可以使用apache commons的多字段key形式的map结构MultiKeyMap
6.排序
可通过Sort对单字段多字段排序
//排序
//单字段排序,根据id排序
((User::getId));
//多字段排序,根据id,年龄排序
((User::getId).thenComparing(User::getAge));
实际上这个写法存在空值安全问题,建议改成
((User::getId,(())).thenComparing(User::getAge,(())));
7.去重
可通过distinct方法进行去重
//去重
List<Long> idList = new ArrayList<Long>();
(1L);
(1L);
(2L);
List<Long> distinctIdList = ().distinct().collect(());
针对属性去重
List<AddOutboundNoticeDetailsBatchVo> entryDetailsBatchDistinctBatchIdList = ().filter(distinctByKey(b -> ())).collect(());
//distinctByKey自己定义
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> ((t), ) == null;
}
8.获取list某个字段组装新list
//获取list对象的某个字段组装成新list
List<Long> userIdList = ().map(a -> ()).collect(());
9.批量设置list列表字段为同一个值
().forEach(a -> ("0"));
10.不同实体的list拷贝
List<TimePeriodDate> timePeriodDateList1 = ().map(p->{TimePeriodDate e = new TimePeriodDate(); (());(()); return e;}).collect(());