数据(测试)
说明:泛型String可以灵活,判断条件也是
List<String> list = Arrays.asList("aa", "ccc", "ddd", "bbb", "ccc");
或者
List<Integer> list = Arrays.asList(11, 22, 33, 44, 55);
打印(遍历)
以前的写法
for (String s : list) {
System.out.println(s);
}
使用lambda的写法
list.forEach(System.out::println);
或1
list.forEach(s -> System.out.println(s));
或2
list.forEach(s -> {
System.out.println(s);
});
排序
以前的写法
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
使用lambda的写法
Collections.sort(list, (o1, o2) -> o1.compareTo(o2));
或对象
// 倒序
List<Personal> newList = list.stream().sorted(Comparator.comparing(Personal::getAge).reversed()).collect(Collectors.toList());
删除 .reversed() 为正序
判断是否存在
以前的写法
for(String s : list) {
if(s.equals("ddd")) {
return true;
}
}
return false;
使用lambda的写法
boolean b = list.stream().anyMatch(s -> s.equals("ccc"));
或
boolean b1 = list.stream().filter(s -> s.equals("ccc")).findFirst().isPresent();
判断存在的值,并返回list
以前的写法
List<String> list2 = new ArrayList<>();
for(String s : list) {
if(s.equals("ddd")) {
list2.add(s);
}
}
使用lambda的写法
List<String> list3 = list.stream().filter(s -> s.equals("ccc")).collect(Collectors.toList());
累加求和
以前的写法
int sum = 0;
for (Integer v : list) {
sum += v;
}
使用lambda的写法
int sum = list.stream().reduce(0, (s, v) -> s + v);
去重
以前的写法
懒得写,Set/Map/List都可以实现
使用lambda的写法
List<String> list2 = list.stream().distinct().collect(Collectors.toList());
或
List<Personal> distinctList = list.stream()
.collect(Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(Personal::getName))), ArrayList::new));
分组
以前的写法
此次省略
lambda的写法
Map<Integer, List<Personal>> map = list.stream().collect(Collectors.groupingBy(Personal::getId));
最大值
Personal max = list.stream().max(Comparator.comparing(Personal::getAge)).get();
最小值
Personal min = list.stream().min(Comparator.comparing(Personal::getAge)).get();
线程
以前的写法
new Thread(new Runnable() {
@Override
public void run() {
// 处理逻辑
}
}).start();
使用lambda的写法文章来源:https://www.toymoban.com/news/detail-618518.html
new Thread(() -> {
// 处理逻辑
}).start();
MyBatis-Plus中用法
使用lambda的写法文章来源地址https://www.toymoban.com/news/detail-618518.html
LambdaQueryWrapper<DictEntity> queryWrapper = Wrappers.lambdaQuery();
// String字符串,判断是否不为空,条件满足,执行判断
queryWrapper.like(StrUtil.isNotBlank(dict.getDictName()), DictEntity::getDictName, dict.getDictName());
// Integer整型,判断是否不等于null,条件满足,执行判断
queryWrapper.like(ObjectUtil.isNotNull(dict.getDictType()), DictEntity::getDictType, dict.getDictType());
获取ID集
List<DeptEntity> deptList = deptService.selectUserDept(uid);
String dids = deptList.stream().map(DeptEntity::getDid).collect(Collectors.joining(","));
到了这里,关于Java JDK1.8 Lambda的多种用法,Lambda的多种写法,Lambda的多种写法比较的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!