stream 过滤返回数据的满足条件的一条数据,否则随机一条数据 java示例代码
时间: 2024-03-06 18:47:02 浏览: 27
好的,以下是一个基于 Java 语言的示例代码,用于从数据流中返回满足条件的一条数据,否则返回随机的一条数据:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Predicate;
public class DataStreamFilter {
public static <T> T filterDataStream(List<T> dataStream, Predicate<T> condition) {
List<T> filteredData = new ArrayList<>();
for (T data : dataStream) {
if (condition.test(data)) {
filteredData.add(data);
}
}
if (!filteredData.isEmpty()) {
// 如果有符合条件的数据,则随机返回一条
Random random = new Random();
return filteredData.get(random.nextInt(filteredData.size()));
} else {
// 如果没有符合条件的数据,则随机返回数据流中的一条
Random random = new Random();
return dataStream.get(random.nextInt(dataStream.size()));
}
}
}
```
这个代码中,我们定义了一个 `filterDataStream` 静态方法,该方法接受两个参数:一个数据流 `dataStream` 和一个条件函数 `condition`。方法会遍历数据流中的所有数据,对于每个数据,判断是否符合条件。如果符合条件,则将该数据加入一个列表 `filteredData` 中。如果 `filteredData` 不为空,则随机返回该列表中的一条数据。否则,随机返回数据流中的一条数据。
您可以根据自己的需要,将这个代码片段作为参考,进行修改和优化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)