说明:泛型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<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的写法
new Thread(() -> {
// 处理逻辑
}).start();
使用lambda的写法
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());