一、list操作分组、过滤、求和、最值、排序、去重。
**
1、通过groupingBy可以分组指定字段
// 分组
Map<String, List<User>> groupBySex = userList.stream().collect(Collectors.groupingBy(User::getSex));
// 遍历分组
for (Map.Entry<String, List<User>> entryUser : groupBySex.entrySet()) {
String key = entryUser.getKey();
List<User> entryUserList = entryUser.getValue();
}
多字段分组
Function<WarehouseReceiptLineBatch, List<Object>> compositeKey = wlb ->
Arrays.<Object>asList(wlb.getWarehouseReceiptLineId(), wlb.getWarehouseAreaId(), wlb.getWarehouseLocationId());
Map<Object, List<WarehouseReceiptLineBatch>> map =
warehouseReceiptLineBatchList.stream().collect(Collectors.groupingBy(compositeKey, Collectors.toList()));
//遍历分组
for (Map.Entry<Object, List<WarehouseReceiptLineBatch>> entryUser : map.entrySet()) {
List<Object> key = (List<Object>) entryUser.getKey();
List<WarehouseReceiptLineBatch> entryUserList = entryUser.getValue();
Long warehouseReceiptLineId = (Long) key.get(0);
Long warehouseAreaId = (Long) key.get(0);
Long warehouseLocationId = (Long) key.get(0);
}
2、过滤:通过filter方法可以过滤某些条件
// 过滤
// 排除掉工号为201901的用户
List<User> userCommonList = userList.stream().filter(a -> !a.getJobNumber().equals("201901")).collect(Collectors.toList());
3、求和:分基本类型和大数类型求和,基本类型先mapToInt,然后调用sum方法,大数类型使用reduce调用BigDecimal::add方法
// 求和
// 基本类型
int sumAge = userList.stream().mapToInt(User::getAge).sum();
// BigDecimal求和
BigDecimal totalQuantity = userList.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimal::add);
上面的求和不能过滤bigDecimal对象为null的情况,可能会报空指针,这种情况,我们可以用filter方法过滤,或者重写求和方法
package com.vvvtimes.util;
import java.math.BigDecimal;
public class BigDecimalUtils {
public static BigDecimal ifNullSet0(BigDecimal in) {
if (in != null) {
return in;
}
return BigDecimal.ZERO;
}
public static BigDecimal sum(BigDecimal ...in){
BigDecimal result = BigDecimal.ZERO;
for (int i = 0; i < in.length; i++){
result = result.add(ifNullSet0(in[i]));
}
return result;
}
}
使用重写的方法
BigDecimal totalQuantity2 = userList.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimalUtils::sum);
判断对象空
stream.filter(x -> x!=null)
stream.filter(Objects::nonNull)
判断字段空
stream.filter(x -> x.getDateTime()!=null)
4、最值
求最小与最大,使用min max方法
// 最小
Date minEntryDate = userList.stream().map(User::getEntryDate).min(Date::compareTo).get();
// 最大
Date maxEntryDate = userList.stream().map(User::getEntryDate).max(Date::compareTo).get();
有时候我们需要知道最大最小对应的这个对象,我们可以通过如下方法获取
Comparator<LeasingBusinessContract> comparator = Comparator.comparing(LeasingBusinessContract::getLeaseEndDate);
LeasingBusinessContract maxObject = leasingBusinessContractList.stream().max(comparator).get();
5、List 转map
/**
* List -> Map
* 需要注意的是:
* toMap 如果集合对象有重复的key,会报错Duplicate key ....
* user1,user2的id都为1。
* 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
*/
Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, a -> a,(k1,k2)->k1));
list转map的时候有时候会将date类型作为key,实际情况中使用string的多,我们可以将某个字段转成string
Map<String, WorkCenterLoadVo> workCenterMap = list.stream().collect(Collectors.toMap(key->DateFormatUtils.format(key.getDate(), "yyyy-MM-dd"), a -> a,(k1,k2)->k1));
6、排序:可通过Sort对单字段多字段排序
// 排序
// 单字段排序,根据id排序
userList.sort(Comparator.comparing(User::getId));
// 多字段排序,根据id,年龄排序
userList.sort(Comparator.comparing(User::getId).thenComparing(User::getAge));
7、去重:可通过distinct方法进行去重
// 去重
List<Long> idList = new ArrayList<Long>();
idList.add(1L);
idList.add(1L);
idList.add(2L);
List<Long> distinctIdList = idList.stream().distinct().collect(Collectors.toList());
针对属性去重
List<AddOutboundNoticeDetailsBatchVo> entryDetailsBatchDistinctBatchIdList = entryDetailsBatchList.stream().filter(distinctByKey(b -> b.getMaterialBatchNumberId())).collect(Collectors.toList());
//distinctByKey自己定义
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
8、获取list某个字段组装新list
// 获取list对象的某个字段组装成新list
List<Long> userIdList = userList.stream().map(a -> a.getId()).collect(Collectors.toList());
9、批量设置list列表字段为同一个值
addList.stream().forEach(a -> a.setDelFlag("0"));
10、不同实体的list拷贝
List<TimePeriodDate> timePeriodDateList1 = calendarModelVoList.stream().map(p->{TimePeriodDate e = new TimePeriodDate(); e.setStartDate(p.getBegin());e.setEndDate(p.getEnd()); return e;}).collect(Collectors.toList());
二、 map的多种循环方式
Map<String, String> map = new HashMap<String, String>();
// 第一种遍历方式
System.out.println("第一种遍历方式:通过遍历 Map 的 keySet,遍历 Key 和 Value");
for (String key : map.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
// 第二种遍历方式(如果在遍历过程中,有删除某些Key-Value的需求,可以使用这种遍历方式)
System.out.println("\n第二种遍历方式:通过Iterator 迭代器遍历 Key 和 Value");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// 第三种遍历方式(推荐,尤其是容量大时)
System.out.println("\n第三种遍历方式:通过遍历 Map 的 entrySet,遍历 Key 和 Value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// 第四种遍历方式
System.out.println("\n第四种遍历方式:通过遍历 Map 的 values,只能遍历 Value,获取不到对应的 Key");
for (String value : map.values()) {
System.out.println("Value: " + value);
}
// 第五种遍历方式(JDK 1.8支持的 Lambda 表达式,强烈推荐!!!)
System.out.println("\n第五种遍历方式:通过 Lambda 表达式,遍历 Key 和 Value");
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
});
三、Optional解决判断Null为空的问题
orElse、orElseGet的用法相当于value值为null时,给予一个默认值:
当user值为null时,orElse函数依然会执行createUsers()方法,而orElseGet函数并不会执行createUsers()
User user = null;
user = Optional.ofNullable(user).orElse(createUsers());
user = Optional.ofNullable(user).orElseGet(() -> createUsers());
public User createUsers(){
User user = new User();
user.setName("Test");
return user;
}
orElseThrow:当value值为null时,直接抛一个异常出去
User user = null;
Optional.orNullable(user).orElseThrow(() -> new Exception("用户不存在"))
判断一个user不为空时,执行业务代码
Optional.ofNullable(user).ifPresent(u->{
// TODO: do something
});
取值某个对象属性的值
// 以前写法
public String getCity(User user) throws Exception{
if(user!=null){
if(user.getAddress()!=null){
Address address = user.getAddress();
if(address.getCity()!=null){
return address.getCity();
}
}
}
throw new Excpetion("取值错误");
}
// java8新写法
public String getCity(User user) throws Exception{
return Optional.ofNullable(user)
.map(u-> u.getAddress())
.map(a->a.getCity())
.orElseThrow(()->new Exception("取指错误"));
}