请举例几种消费型函数式方法
时间: 2024-05-01 10:20:27 浏览: 10
消费型函数式方法是指不返回结果,而是对传入的参数进行操作或消费的方法。以下是几种常见的消费型函数式方法:
1. forEach:遍历集合中的每个元素,并对每个元素进行消费。
```
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println("Hello, " + name));
```
2. peek:类似于 forEach,但是可以在每个元素被消费前后进行操作。
```
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.stream()
.peek(name -> System.out.println("Before consuming: " + name))
.forEach(name -> System.out.println("Hello, " + name));
```
3. accept:接受一个参数并进行消费。
```
Consumer<String> consumer = name -> System.out.println("Hello, " + name);
consumer.accept("Alice");
```
4. removeIf:移除集合中满足条件的元素。
```
List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie"));
names.removeIf(name -> name.startsWith("A"));
```
5. merge:将 Map 中指定 key 对应的 value 与传入的 value 进行合并。
```
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.merge("Alice", 10, (oldValue, newValue) -> oldValue + newValue);
```