“在代码的世界里,每一行都是进步的足迹,每一次挑战都是成长的机遇。”

Lambda表达式,Optional,Consumer常见操作

1. 遍历列表
使用Lambda表达式遍历列表并打印每个元素。
List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
list.forEach(item -> System.out.println(item));
2. 过滤列表
使用Lambda表达式过滤列表,只保留长度大于5的字符串。
List<String> list = Arrays.asList("Apple", "Banana", "Cherry", "Watermelon");
List<String> filteredList = list.stream()
.filter(item -> item.length() > 5)
.collect(Collectors.toList());
3. 转换列表
使用Lambda表达式转换列表,将每个字符串转换为其长度。
List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
List<Integer> lengthList = list.stream()
.map(item -> item.length())
.collect(Collectors.toList());
4. 列表元素求和
使用Lambda表达式计算列表元素的总和。
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int sum = list.stream()
.reduce(0, (a, b) -> a + b);
5. 排序列表
使用Lambda表达式对列表进行排序。
List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
List<String> sortedList = list.stream()
.sorted((a, b) -> a.compareTo(b))
.collect(Collectors.toList());
1. 分组
使用Lambda表达式将列表按照某个属性进行分组。
List<String> list = Arrays.asList("Apple", "Banana", "Cherry", "Apple", "Cherry", "Banana", "Apple");
Map<String, Long> grouped = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
2. 查找最大值和最小值
使用Lambda表达式查找列表中的最大值和最小值。
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int max = list.stream()
.max(Integer::compareTo)
.orElse(null);
int min = list.stream()
.min(Integer::compareTo)
.orElse(null);
3. 并行处理
使用Lambda表达式进行并行处理。
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.parallelStream()
.forEach(item -> System.out.println(item));
4. 连接字符串
使用Lambda表达式连接字符串。
List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
String joined = list.stream()
.collect(Collectors.joining(", "));
5. 去重
使用Lambda表达式去除列表中的重复元素。
List<String> list = Arrays.asList("Apple", "Banana", "Cherry", "Apple", "Banana");
List<String> distinctList = list.stream()
.distinct()
.collect(Collectors.toList());

以下是一些使用Consumer的例子:
1. 基本使用
创建一个Consumer对象,然后使用它来打印一个字符串。
Consumer<String> consumer = (t) -> System.out.println(t);
consumer.accept("Hello, World!");
2. 在列表中使用
使用Consumer来遍历一个列表,并打印每个元素。
List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
Consumer<String> consumer = (t) -> System.out.println(t);
list.forEach(consumer);
3. 链式使用
使用andThen方法来链接两个Consumer对象。
Consumer<String> consumer1 = (t) -> System.out.println("Consumer 1: " + t);
Consumer<String> consumer2 = (t) -> System.out.println("Consumer 2: " + t);
consumer1.andThen(consumer2).accept("Hello, World!");
1. 创建Optional
使用Optional.of()创建一个包含非null值的Optional,使用Optional.empty()创建一个不包含值的Optional。
Optional<String> optional1 = Optional.of("Hello, World!");
Optional<String> optional2 = Optional.empty();
2. 使用isPresent()检查Optional是否包含值
Optional<String> optional = Optional.of("Hello, World!");
if (optional.isPresent()) {
System.out.println(optional.get());
}
3. 使用ifPresent()方法
ifPresent()方法接受一个Consumer参数,如果Optional包含值,那么就对该值执行Consumer的操作。
Optional<String> optional = Optional.of("Hello, World!");
optional.ifPresent(System.out::println);
4. 使用orElse()提供默认值
orElse()方法在Optional不包含值时,提供一个默认值。
Optional<String> optional = Optional.empty();
String value = optional.orElse("Default Value");
5. 使用orElseGet()提供默认值
orElseGet()方法和orElse()方法类似,但是它接受一个Supplier接口的实现,可以提供更复杂的默认值。
Optional<String> optional = Optional.empty();
String value = optional.orElseGet(() -> "Default Value");
6. 使用orElseThrow()抛出异常
orElseThrow()方法在Optional不包含值时,抛出一个异常。
Optional<String> optional = Optional.empty();
String value = optional.orElseThrow(IllegalStateException::new);
7. 使用map()和flatMap()方法
map()和flatMap()方法可以对Optional中的值进行转换。
Optional<String> optional = Optional.of("Hello, World!");
Optional<Integer> lengthOptional = optional.map(String::length);
Optional<Integer> lengthOptional2 = optional.flatMap(s -> Optional.of(s.length()));

Stream API
1. 过滤
使用filter方法过滤出符合条件的元素。
List<String> names = Arrays.asList("John", "Jane", "Tom", "Bob", "Alice");
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("J"))
.collect(Collectors.toList());
2. 映射

使用map方法将每个元素转换为另一种形式。

List<String> names = Arrays.asList("John", "Jane", "Tom", "Bob", "Alice");
List<Integer> nameLengths = names.stream()
.map(String::length)
.collect(Collectors.toList());
3. 排序

使用sorted方法对元素进行排序。

List<String> names = Arrays.asList("John", "Jane", "Tom", "Bob", "Alice");
List<String> sortedNames = names.stream()
.sorted()
.collect(Collectors.toList());
4. 查找

使用findAny或findFirst方法查找符合条件的元素。

List<String> names = Arrays.asList("John", "Jane", "Tom", "Bob", "Alice");
Optional<String> anyNameStartingWithJ = names.stream()
.filter(name -> name.startsWith("J"))
.findAny();
5. 匹配
使用anyMatch, allMatch或noneMatch方法检查是否有元素符合条件。
List<String> names = Arrays.asList("John", "Jane", "Tom", "Bob", "Alice");
boolean anyNameStartingWithJ = names.stream()
.anyMatch(name -> name.startsWith("J"));
6. 聚合
使用reduce方法将所有元素聚合成一个元素。
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, Integer::sum);
7. 分组
使用collect方法和Collectors.groupingBy函数进行分组。
List<String> names = Arrays.asList("John", "Jane", "Tom", "Bob", "Alice", "John", "John");
Map<String, Long> nameFrequencies = names.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

public List<MyVO> searchWithPagination(String keyword, int pageSize, int pageNumber) {
List<MyVO> allResults = getAllData();

// 过滤出包含关键词的数据
List<MyVO> filteredResults = allResults.stream()
.filter(vo -> vo.getLevel1().contains(keyword) || vo.getLevel2().contains(keyword) || vo.getLevel3().contains(keyword) || vo.getLevel4().contains(keyword))
.collect(Collectors.toList());

// 在内存中进行分页
int fromIndex = (pageNumber - 1) * pageSize;
int toIndex = Math.min(fromIndex + pageSize, filteredResults.size());

return filteredResults.subList(fromIndex, toIndex);
}

Write your comment Here