0%

Java Lambda 基础使用

JDK 8 新特性,记录了一些基本使用方法

Lambda

JDK1.8/8新特性

下面是一些使用方法

函数式接口

仅包含一个方法的接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}

使用方法

1
2
3
4
5
6
7
8
public static void main(String[] args) {
Runnable runnable = () -> {
System.out.println("多线程");
};

Thread thread = new Thread(runnable, "Thread");
thread.start();
}

多个list合并成一个list

1
List taskKpiList = taskDetailVO.getTaskTypeList().stream().map(PerfEvaluateTaskTypeVO::getTaskKpiList).flatMap(Collection::stream).collect(Collectors.*toList*());

判空

1
String gradeName = Optional.ofNullable(evaluationLevel).map(PerfEvaluationLevelModel::getGradeName).orElse("");

去重

1
2
3
itemAuditsModels = itemAuditsModels.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(EmployeeBaseInfoModel::getEmployeeId))), ArrayList::new))

分组统计

1
Map<String, Long> taskUserCountMap = list.stream().collect(Collectors.groupingBy(ReportUserTaskExcelVO::getTaskUserId, Collectors.counting()));

integer求和

1
todoNumDtoList.stream().map(WorkBenchTodoNumDto::getNum).reduce(Integer::sum).orElse(0)

有序分组

1
LinkedHashMap<String, Long> taskUserCountMap = list.stream().collect(Collectors.groupingBy(ReportUserTaskExcelVO::getTaskUserId, LinkedHashMap::new, Collectors.counting()));

取某个字段最小的记录

1
bookList.stream().min(Comparator.comparing(Book::getSort)).get();

map删除

1
2
3
4
5
6
7
itemMap.entrySet().removeIf(entry -> {
KanbanItemVO itemVO = entry.getValue();
if (BusinessConstant.TRUE.equals(itemVO.getIsDeleted()) && BigDecimal.ZERO.compareTo(itemVO.getProgress()) == 0){
return true;
}
return false;
});

排序字段存在null

1
2
3
4
return list.stream().sorted(Comparator.comparing(ReportYearCountVO::getFinalScore, Comparator.nullsLast(BigDecimal::compareTo))).collect(Collectors.toList());
return list.stream().sorted(Comparator.comparing(ReportYearCountVO::getFinalScore, Comparator.nullsFirst(BigDecimal::compareTo))).collect(Collectors.toList());
nullsLast:null放在最后
nullsFirst:null放在最前面

BigDecimal分组求和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
List<DepartmentEntity> ds = new List<DepartmentEntity>();
//假设集合中已有数据………………
//1、先对集合根据名称进行分组,此时 List<DepartmentEntity> 已转为以名称(name)属性为key的 Map<String,List<DepartmentEntity>>
Map<String,BigDecimal> moneySumGroupByName = ds.stream().collect(Collectors.groupingBy(DepartmentEntity::getName))
//2、此时利用 Map 的 entrySet() 方法得到 ,得到 Map.Entry 的 Set 集合
.entrySet()
//3、对 Set 集合进行 toMap,此时新 Map 的 key 继续使用 Map.Entry 的 key ,也就是名称;
//在处理 value 时,因为此时value是已经根据名称分组后的集合,所以这里直接进行集合求和即可
.stream().collect(Collectors.toMap(Map.Entry::getKey,m->m.getValue()
.stream()
//3、过滤非空
.filter(d->Objects.nonNull(d.getMoney()))
//4、stream 对 BigDecimal 的求和
.map(DepartmentEntity::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add)));

map转list

1
quarterMap.entrySet().stream().map(entry -> TaskExecuteQuarterModel.builder().quarter(entry.getKey()).taskExecuteList(entry.getValue()).build()).collect(Collectors.toList());

排序

list = list.stream().sorted(Comparator.comparing(WaterCurrentDto::getCs, Comparator.nullsLast(String::compareTo).reversed())
        .thenComparing(WaterCurrentDto::getCAll, Comparator.nullsLast(BigDecimal::compareTo).reversed())).collect(Collectors.toList());