stream流怎么使用代码示例
时间: 2024-04-21 14:06:25 浏览: 72
以下是一个使用stream流的代码示例,通过stream流可以对集合进行一系列的操作:
```
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");
// 使用filter过滤集合中的元素,只保留长度大于5的字符串
List<String> filteredFruits = fruits.stream()
.filter(fruit -> fruit.length() > 5)
.collect(Collectors.toList());
System.out.println("Filtered fruits: " + filteredFruits);
// 使用map将集合中的元素映射为新的对象
List<Fruit> fruitObjects = fruits.stream()
.map(fruit -> new Fruit(fruit))
.collect(Collectors.toList());
System.out.println("Fruit objects: " + fruitObjects);
// 使用reduce将集合中的元素进行累加
int totalLength = fruits.stream()
.mapToInt(fruit -> fruit.length())
.reduce(0, (a, b) -> a + b);
System.out.println("Total length of all fruits: " + totalLength);
}
static class Fruit {
String name;
Fruit(String name) {
this.name = name;
}
@Override
public String toString() {
return "Fruit{" +
"name='" + name + '\'' +
'}';
}
}
}
```
输出结果:
```
Filtered fruits: [cherry, elderberry]
Fruit objects: [Fruit{name='apple'}, Fruit{name='banana'}, Fruit{name='cherry'}, Fruit{name='date'}, Fruit{name='elderberry'}]
Total length of all fruits: 34
```
阅读全文